Constructors
A constructor is similar to a function in terms of writing the code except the following differences.
- Constructor name and class name will be same.
- Constructor doesn't has any return type not even void.
Behavior of Constructor:
- A constructor executes automatically whenever an object is created.
- Constructors can be overloaded.
- 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.
- Destructors cannot be overloaded.
- 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
- using System;
- class A
- {
- public A()
- {
- Console.WriteLine("Constructor called");
- }
- public void Display()
- {
- Console.WriteLine("welcome to C#.net");
- }~A()
- {
- Console.WriteLine("Destructor called");
- }
- }
- class Demo
- {
- public static void Main()
- {
- A obj = new A();
- obj.Display();
- }
- }
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:
- using System;
- class A
- {
- private int x, y, z;
- public A(int p, int q)
- {
- x = p;
- y = q;
- }
- public int Add()
- {
- z = x + y;
- return (z);
- }
- }
- class Demo
- {
- public static void Main()
- {
- A obj = new A(2015, 1);
- int r;
- r = obj.Add();
- Console.WriteLine("Sum of two numbers is {0}", r);
- }
- }
Output:
Sum of two numbers is 2016