Constructors in C# - Part 1

Constructors

A constructor is similar to a function in terms of writing the code except the following differences.

  1. Constructor name and class name will be same.
  2. Constructor doesn't has any return type not even void.

Behavior of Constructor:

  1. A constructor executes automatically whenever an object is created.
  2. Constructors can be overloaded.
  3. Constructors can have arguments.

Destructors:

Destructors are executed automatically whenever an object is released from the memory.

Destructors name will be similar to the class name but it is predefined with ~ (tilde) symbol.

  1. Destructors cannot be overloaded.
  2. Destructors doesn't have arguments.

Default Constructor:

Every class consists of a constructor internally .it doesn't takes any arguments and it doesn't performs any task. It is a null constructor, this constructor doesn't works when a programmer has return any constructor.

Example

  1. using System;  
  2. class A  
  3. {  
  4.     public A()  
  5.     {  
  6.         Console.WriteLine("Constructor called");  
  7.     }  
  8.     public void Display()  
  9.     {  
  10.         Console.WriteLine("welcome to C#.net");  
  11.     }~A()  
  12.     {  
  13.         Console.WriteLine("Destructor called");  
  14.     }  
  15. }  
  16. class Demo  
  17. {  
  18.     public static void Main()  
  19.     {  
  20.         A obj = new A();  
  21.         obj.Display();  
  22.     }  
  23. }  
Output

Constructor called
welcome to C#.net
Destructor called


Purpose of constructor

A constructor is mainly used for initialization of object with certain values (i.e. numbers).

Note: Constructors are used when certain input has to pass down compulsary to an object other wise the program may not work.

Constructor Parameters:

Example:
  1. using System;  
  2. class A  
  3. {  
  4.     private int x, y, z;  
  5.     public A(int p, int q)  
  6.     {  
  7.         x = p;  
  8.         y = q;  
  9.     }  
  10.     public int Add()  
  11.     {  
  12.         z = x + y;  
  13.         return (z);  
  14.     }  
  15. }  
  16. class Demo  
  17. {  
  18.     public static void Main()  
  19.     {  
  20.         A obj = new A(2015, 1);  
  21.         int r;  
  22.         r = obj.Add();  
  23.         Console.WriteLine("Sum of two numbers is {0}", r);  
  24.     }  
  25. }  
Output:

Sum of two numbers is 2016