Close
Close

C# Classes and Objects


We are going to make our own class in this chapter. As stated in the previous chapter, a class can have its own data members (fields), methods, etc.

We define a class using the class keyword.

class ClassName
{

}

Here, we have used the class keyword to define a class with a name ClassName. We can also have some fields or methods inside our class.

class ClassName
{
    public int x;
    public double y;

    public void MethodName()
    {
        //method definition
    }
}

x and y are member variables of the class ClassName and MethodName is a method of the class ClassName.

We have used a keyword public before the variables x, y, and the method MethodName. public is a modifier which we will explain soon.

Let's take an example and create a class.

using System;

class Student
{
  public int rollNumber;
  public string name;
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student();
    s.rollNumber = 1;
    s.name = "Andrew";

    Console.WriteLine(s.rollNumber);
    Console.WriteLine(s.name);
  }
}
Output
1
Andrew

Let's go through this code to understand how to make our own class.

class Student → We have defined our own class named Student using the class keyword.

Inside the Student class, we declared two variables (member variables or fields) - rollNumber and name. These variables belong to the class Student since these are declared inside this class and thus are called members of the class.

Remember that the execution of any program begins with the Main method. So the execution of the above code will start from the first statement of the Main method.

Student s = new Student() → This statement declares s as an object of class Student. We use the new keyword to make an object of any class. It is the same as saying that s is a Student.

Student s = new Student(); created a new object of the class Student. Since the Student has rollNumber and name as its member, therefore s will also have a name and a rollNumber.

s.rollNumber = 1; → We are setting the roll number of the object s.

s.name = "Andrew"; → We are setting the name of the object s.

As you can see, we access any field of an object using a dot (.).

We can also have methods inside a class. Let's take an example.

using System;

class Student
{
  public int rollNumber;
  public string name;

  public void SetName(string n)
  {
    name = n;
  }
  public string GetName()
  {
    return name;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student();
    s.rollNumber = 1;

    s.SetName("Andrew");

    string a = s.GetName();

    Console.WriteLine(a);
  }
}
Output
Andrew

In the above example, GetName and SetName are two methods inside the Student class which we used to get and set the value of the variable name respectiely.

s.SetName("Andrew"); → We called the method SetName on the object s of the Student class.

string a = s.GetName(); → Similarly, we called the method GetName on s.

C# Access Modifiers


The access modifiers decide how the members of a class can be accessed. There are five types of access modifiers in C#.

  • Public
  • Private
  • Protected
  • Internal
  • Protected Internal

public


We are already using public in the above examples. When a data member or a method is declared as public, it becomes available everywhere in the program, even outside the class in which it was declared. For example, the variables rollNumber and name are declared public in the above example. And that's why they were even accessible inside the Test class (outside Student class).

private


When we declare a data member or a method as private, it can't be accessed outside the class in which it is defined. Let's take an example.

using System;

class Student
{
  private int rollNumber;
  private string name;

  public void SetName(string n)
  {
    name = n;
  }
  public string GetName()
  {
    return name;
  }

  public void SetRollNumber(int r)
  {
    rollNumber = r;
  }
  public int GetRollNumber()
  {
    return rollNumber;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student();
    s.SetRollNumber(1);

    s.SetName("Andrew");

    string a = s.GetName();

    Console.WriteLine(a);
  }
}
Output
Andrew

In the above example, the data members name and rollNumber are declared as private but the methods are all public. We are able to access the variables inside the methods because the methods are in the same class. And we accessed the methods inside Test class because they are public.

However, if we try to access the private members outside its class, we would get an error.

using System;

class Student
{
  private int rollNumber;
  private string name;
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student();
    s.rollNumber = 1;
  }
}
Output
file.cs(14,7): error CS0122: `Student.rollNumber' is inaccessible due to its protection level

Protected


Protected is similar to private. Any member declared as protected cannot be accessed outside the class but can be accessed by any subclass of that class.

We will learn more about subclass in a later chapter.

We are also going to study internal and protected internal later.

C# Constructor


A constructor is a special member method of a class which is called automatically when an object of that class is made. It has the same name as that of the class and has no return type.

Constructor is a special type of function which is used to initialize an object. It is invoked at the time of object creation.
using System;

class Rectangle
{
  private int length;
  private int breadth;

  public Rectangle()
  {
    length = 10;
    breadth = 20;
  }

  public void Display()
  {
    Console.WriteLine($"Length is {length}\nBreadth is {breadth}");
  }
}

class Test
{
  static void Main(string[] args)
  {
    Rectangle r = new Rectangle();
    r.Display();
  }
}
Output
Length is 10
Breadth is 20

In this example when we created the object r of the class Rectangle, the constructor Rectangle() automatically got called and initialized the data members for the object r. It initialized the length and breadth of r to 10 and 20 respectively.

When the object of the class Rectangle was made, the constructor (method of Rectangle with the same name as of class name) called and the values of length and breadth were assigned inside it.

We can also make a constructor with nothing in its body.
Rectangle(){ };

Constructor Having Parameters


We can also have constructors with parameters.

using System;

class Rectangle
{
  private int length;
  private int breadth;

  public Rectangle(int l, int b)
  {
    length = l;
    breadth = b;
  }

  public void Display()
  {
    Console.WriteLine($"Length is {length}\nBreadth is {breadth}");
  }
}

class Test
{
  static void Main(string[] args)
  {
    Rectangle r = new Rectangle(10, 20);
    r.Display();
  }
}
Output
Length is 10
Breadth is 20

In this example, we have parameters in our constructor. As told earlier, a constructor is also a method which is executed at the time of creating an object and has the same name as that of its parent class. So, it will work like a method and assign values passed from new Rectangle (10, 20); to length and breadth.

It will create an object r of class Rectangle and pass 10 to l and 20 to b (l and b are used in the constructor of the class Rectangle).

C# Destructor


Destructors are methods which are just the opposite of constructors. Destructors destroy the object whenever the object goes out of scope.

It has the same name as that of the class with a tilde (~) sign before it.

class A
{
        ~A();
};

Here, ~A() is the destructor of class A.

Destructors don't take any argument and have no return type.

When is a destructor called?


A destructor gets automatically called when the object goes out of scope. We know that a non-parameterized constructor gets automatically called when an object of the class is created. Exactly opposite to it, a destructor gets called when the object goes out of scope and destroys the object.

using System;

class Rectangle
{
  private int length;
  private int breadth;

  public Rectangle()
  {
    Console.WriteLine("Constructor");
  }

  ~Rectangle()
  {
    Console.WriteLine("Destructor");
  }
}

class Test
{
  static void Main(string[] args)
  {
    Rectangle r;

    r = new Rectangle();
  }
}
Output
Constructor
Destructor

In this example, when the object r of class Rectangle was created, its constructor was called, no matter in what order we define it in the class. At last, when the object went out of scope, its destructor got called.

Note that the destructor will get automatically called even if we do not explicitly define it in the class.

C# Use of Static


static is used to make access to any data variable or method without making an object of that class. Let's take an example.

using System;

class Rectangle
{
  public static void PrintArea(int l, int b)
  {
    Console.WriteLine($"Area is {l*b}");
  }
}

class Test
{
  static void Main(string[] args)
  {
    Rectangle.PrintArea(2, 4);
  }
}
Output
Area is 8

Our method PrintArea is static. So, we directly used it on Rectangle class (Rectangle.PrintArea(2, 4)), without making any object of it.

In the next example, we have made a static variable. Let's have a look.

using System;

class Student
{
  public static string s = "Inside student class";
}

class Test
{
  static void Main(string[] args)
  {
    Console.WriteLine(Student.s);
  }
}
Output
Inside student class

Here, the variable s is made static and thus, we directly accessed it in the Main function.

C# Static Constructor


We can also have a static constructor. A static constructor can't have any parameters or modifier. It is invoked only once during the creation of the first instance of the class. We use a static constructor to set data to static members.

If a data is static, we will use it without the creation of any object. So, it doesn't vary with different objects. So, we use a static constructor to set its value because a static constructor is only executed during the creation of the first object. We can also use a static constructor to perform a task which is required to perform only once.

using System;

class Circle
{
  public static double pi;
  private int radius;

  public Circle(int r)
  {
    radius = r;
  }

  static Circle()
  {
    pi = 3.14;
    Console.WriteLine("Static Constructor");
  }

  public void PrintArea()
  {
    Console.WriteLine(pi*radius*radius);
  }
}

class Test
{
  static void Main(string[] args)
  {
    Circle a = new Circle(2);
    Circle b = new Circle(3);

    a.PrintArea();
    b.PrintArea();
  }
}
Output
Static Constructor
12.56
28.26

In this example, we used the static constructor to set the value of static variable pi. The static constructor ran only once during the creation of the first object a and not the second time.

Returning and Passing Object in a Method in C#


Yes, we can return or pass object(s) to a method. Let's see an example.

using System;

class Account
{
  public int balance;

  public Account()
  {
    balance = 0;
  }

  public static Account GetAcc(Account a, Account b)
  {
    Account ac = new Account();
    ac.balance = a.balance+b.balance;
    return ac;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Account a1, a2;

    a1 = new Account();
    a2 = new Account();

    a1.balance = 50;
    a2.balance = 60;
    Account b = Account.GetAcc(a1,a2);

    Console.WriteLine(b.balance);
  }
}
Output
110

As you have seen, our method GetAcc is creating an Account object by taking two Account objects and returning it also.

b = Account.getAcc(a1,a2);GetAcc will create and return a new Account object and b will become equal to that object.

Objects are reference type.

C# this


Consider the following code sinppet:

class ClassName
{
    public int value;

    public void ClassName(int x)
    {
        value = x;
    }
}

Take a look at the line value = x. We are basically setting the value of the variable value of the current instance i.e., the value of the variable of class on which the method has been called.

We can use this keyword to refer to the current instance of the class. For example, this.value means the variable value of the current object which is calling the method.

Let's look at an example.

using System;

class Student
{
  public string name;

  public Student(string s)
  {
    this.name = s;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student("XYZ");
    Console.WriteLine(s.name);
  }
}
Output
XYZ

In this.name = s;, it means that the variable name of the object which has called this method.

Let's take one more example.

using System;

class Student
{
  public string name;

  public Student(string name)
  {
    this.name = name;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student s = new Student("XYZ");
    Console.WriteLine(s.name);
  }
}
Output
XYZ

public Student(string name)
{
    public int value;

    this.name = name;
}

Here, name in this.name referes to the variable name of the current instance of the class and another name referes to the name passed to the method - Student(string name).

We can also use this to pass the current object to a method.

C# Collection of Objects


We can also use objects in an array or collections like a List similar to data types. Let's take an example of creating an array of objects.

using System;

class Student
{
  public string name;

  public Student(string name)
  {
    this.name = name;
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student[] s = new Student[10];

    s[0] = new Student("ABC");

    Console.WriteLine(s[0].name);
  }
}
Output
ABC

C# Constructor Overloading


Suppose we have a Student class and while making its object, we want to pass a name to it and if nothing is passed then the name should be "unknown". And yes! we can do this by having two constructors. Let's look at an example.

using System;

class Student
{
  public string name;

  public Student()
  {
    name = "unknown";
  }

  public Student(string name)
  {
    this.name = name;
  }

  public void PrintName()
  {
    Console.WriteLine(this.name);
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student a, b;
    a = new Student("xyz");
    b = new Student();

    a.PrintName();
    b.PrintName();
  }
}
Output
xyz
unknown

This is called constructor overloading.

Now let's understand this example. Here, we made two objects of the class Student. While creating an object a, we passed a string "xyz" to the object as new Student ("xyz"). This invoked the constructor having a string parameter - Student(string name).

Similarly, while creating a second object b of the class Student, we didn't pass anything to the object b as b = new Student(). So, the constructor having no parameter Student() got invoked and initialized the name with the value "unknown".

Conditions for Constructor Overloading


The conditions for constructor overloading is:

  • Either all constructor have a different number of parameters
  • or all constructors have different types of parameters
  • or the order of parameters is different for all constructors

In this chapter, you have learned all the basics of objected oriented programming in C#. From the next chapter, we will dig much deeper.


Ask Yours
Post Yours
Doubt? Ask question