Monday, December 21, 2009

Constructors in C#

The On Demand Global Workforce - oDesk

If you go through any standard C# books you will see the constructors and so I would not get into the details of the constructors but what is more important to me is the use of static constructors which is somethine new in C# or you can say that its a copy of initiliazation block in Java.

Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization. If a class is not defined with the constructor then the CLR (Common Language Runtime) will provide an implicit constructor which is called as Default Constructor. A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.
  • Constructors do not return a value.
  • Constructors can be overloaded.
  • If a class is defined with static and Non-static constructors then the privilege will be given to the Non-static constructors.
The following are the access modifiers for constructors,
  • Public : A constructor that is defined as public will be called whenever a class is instantiated.
  • Protected : A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created.
  • Private : A constructor is defined as private in such cases whenever a class which contains only static members has to be accessed will avoid the creation of the object for the class.
  • Internal : An internal constructor can be used to limit concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.
  • External : When a constructor is declared using an extern modifier, the constructor is said to be an external constructor.
Types of Constructors
  1. Static : Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.


    Code: CSharp
    Static ClassName() { //Initialization statements; }


  2. Non-Static : are used for initializing the Non-Static and Static members of a class. These will be invoked everytime a new object is defined for a class.


    Code: CSharp
    Public ClassName([argsInfo]) { //Initialization statements; }



Using Constructors (C# Programming Guide)
Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class, and usually initialize the data members of the new object.
In the following example, a class called Taxi is defined with a simple constructor. This class is then instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after memory is allocated for the new object.

C#
public class Taxi
{
public bool isInitialized;
public Taxi()
{
isInitialized = true;
}
}

class TestTaxi
{
static void Main()
{
Taxi t = new Taxi();
System.Console.WriteLine(t.isInitialized);
}
}

A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new. For more information, see Instance Constructors.
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation. For more information, see Static Classes and Static Class Members.
You can prevent a class from being instantiated by making the constructor private, as follows:

C#
class NLog
{
// Private Constructor:
private NLog() { }

public static double e = System.Math.E;  //2.71828...
}

For more information, see Private Constructors.
Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default values shown in the Default Values Table. However, this default constructor is only invoked if the struct is instantiated with new. For example, this code uses the default constructor for Int32, so you are assured that the integer is initialized:

int i = new int();
Console.WriteLine(i);

The following code, however, results in Compiler Error CS0165 because it does not use new, and because it attempts to use an object that has not been initialized:

int i;
Console.WriteLine(i);

Alternatively, objects based on structs can be initialized or assigned and then used, like this:

int a = 44;  // Initialize the value type...
int b;
b = 33;      // Or assign it before using it.
Console.WriteLine("{0}, {1}", a, b);

So calling the default constructor for a value type is not required.
Both classes and structs can define constructors that take parameters. Constructors that take parameters must be called through a new statement or a base statement. Classes and structs can also define multiple constructors, and neither is required to define a default constructor. For example:

C#
public class Employee
{
public int salary;

public Employee(int annualSalary)
{
salary = annualSalary;
}

public Employee(int weeklySalary, int numberOfWeeks)
{
salary = weeklySalary * numberOfWeeks;
}
}

This class can be created using either of the following statements:

C#
Employee e1 = new Employee(30000);
Employee e2 = new Employee(500, 52);

A constructor can use the base keyword to call the constructor of a base class. For example:

C#
public class Manager : Employee
{
public Manager(int annualSalary)
: base(annualSalary)
{
//Add further instructions here.
}
}

In this example, the constructor for the base class is called before the block for the constructor is executed. The base keyword can be used with or without parameters. Any parameters to the constructor can be used as parameters to base, or as part of an expression. For more information, see base.
In a derived class, if a base-class constructor is not called explicitly using the base keyword, then the default constructor, if there is one, is called implicitly. This means that the following constructor declarations are effectively the same:

C#
public Manager(int initialdata)
{
//Add further instructions here.
}

C#
public Manager(int initialdata) : base()
{
//Add further instructions here.
}

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor using base.
A constructor can invoke another constructor in the same object using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression. For example, the second constructor in the previous example can be rewritten using this:

C#
public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}

The use of the this keyword above causes this constructor to be called:

C#
public Employee(int annualSalary)
{
salary = annualSalary;
}

Constructors can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can construct the class. For more information, see Access Modifiers.
A constructor can be declared static using the static keyword. Static constructors are called automatically, immediately before any static fields are accessed, and are normally used to initialize static class members. For more information, see Static Constructors.