Pages

Men

rh

6/16/2012

Constructors in C#

Constructors:
  • Constructors are class methods that are executed when an object of a class or struct is created. They have the same name as the class or struct, and usually initialize the data members of the new object.
  • A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.
  •  If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values as listed in
  •  Constructor do not have any return type even Void.
Types of Constructors:
  •  Instance constructors
  • Private Constructors
  • Static Constructors
  • Default Constructor
Instance Constructors:
Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.

The following example shows an instance constructor:

class CoOrds
{
    public int x, y;
 
    // constructor
    public CoOrds()
    {
        x = 0;
        y = 0;
    }
}
 
This instance constructor is called whenever an object based on the CoOrds class is created. A constructor like this one, which takes no arguments, is called a default constructor. However, it is often useful to provide additional constructors. For example, we can add a constructor to the CoOrds class that allows us to specify the initial values for the data members:
// tcA constructor with two arguments:
public CoOrds(int x, int y)
{
    this.x = x;
    this.y = y;
}
This allows CoOrd objects to be created with default or specific initial values, like this:
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
 
If a class does not have a constructor, a default constructor is automatically generated and default values are used to initialize the object fields.

Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class through the initializer, as follows:
 
class Circle : Shape
{
    public Circle(double radius)
        : base(radius, 0)
    {
    }
}
 
Private Constructor:
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class

Example:
               class NLog
{
    // Private Constructor:
    private NLog() { }
 
    public static double e = Math.E;  //2.71828...
}

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

The following is an example of a class using a private constructor.
public class Counter
{
    private Counter() { }
    public static int currentCount;
    public static int IncrementCount()
    {
        return ++currentCount;
    }
}
 
class TestCounter
{
    static void Main()
    {
        // If
 
 
 
 you uncomment the following statement, it will generate
        // an error because the constructor is inaccessible:
        // Counter aCounter = new Counter();   // Error
 
        Counter.currentCount = 100;
        Counter.IncrementCount();
        Console.WriteLine("New count: {0}", Counter.currentCount);
 
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: New count: 101

Static Constructor:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
Example:
class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;
 
    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}
 
Static constructors have the following properties:
  •  A static constructor does not take access modifiers or have parameters.
  •  A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  •  A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  •  A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
Default Constructor
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.

Constructor Overloading

C# supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can be like this:
public class mySampleClass
{
    public mySampleClass()
    {
        // This is the no parameter constructor method.
        // First Constructor
    }
 
    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
 
    }
 
    public mySampleClass(int Age, string Name)
    {
        // This is the constructor with two parameters.
        // Third Constructor
    }
 
    // rest of the class members goes here.
}
Calling Constructor from another Constructor
You can always make a call to one constructor from within another. Say, for example:
public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }
 
    public mySampleClass(int Age) 
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}

No comments :

Post a Comment