Archive for June 26th, 2012

Constructors and Destructors (C#)

This is for my quick references and I have taken most of the information from MSDN and other web sites. BTW I have written and tested the source!

Constructors
– Constructors are methods that are executed when an object of a class is created.
– They have the same name as the class.
– A class  may have multiple constructors that take different arguments.
– Constructors enable the programmer to set default values.
– Like class, structs also can have constructors.

There are 3 kind of constructors in .Net (as far as I know), they are

  • Instance Constructors -Used to create and initialize instances of the class
  • Private Constructors – A special type of instance constructor that is not accessible outside the class (cannot be instantiated)
  • Static Constructors – Automatically initialize the class before the first instance is created or any static members are referenced
Example:
public class A //Class Name A
{
public int i;
public A() // Constructor of A
{
i=1;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A(); //Initiated with new Operator
Console.WriteLine("The initialized value is: {0}", a.i);

System.Console.ReadLine(); //This line is to stop the result window
}
}

Destructors
– are used to destruct instances of classes.
– cannot be defined in structs. They are only used with classes.
– A class can only have one destructor.
– cannot be inherited or overloaded.
– cannot be called. They are invoked automatically
– does not take modifiers or have parameters.

Example:
class A
{
public A()
{
Console.WriteLine("Constructor");
}
~A()
{
Console.WriteLine("Destructor");
}
}

 

class Program
{
static void Main(string[] args)
{
A a = new A(); //Initiated with new Operator

System.Console.ReadLine(); //This line is to stop the result window
}
}
Advertisement

Leave a comment