Types of Constructor in .Net

Nakul.Lande
Posted by in OOPS category on for Intermediate level | Points: 250 | Views : 14462 red flag

In this article, we shall learn about different types of constructors in C#.NET.

Introduction


Constructor is nothing but a function (with the same name as Class) and is used for initializing the members of a class whenever an class object is created. You can initialize the members with any value (as per member datatype) or with the default values through constructor.

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.

Some of the basic properties of Constructor are :
a. Constructors do not return a value.
b. Constructors can be overloaded.
c. If a class is defined with static and Non-static constructors then the privilege will be given to the Non-static constructors.

Objective

The objective of this article to understand different types of constructor (Public,private, protected) and their uses.

Using the code


A. Public Constructor: 

These are the most common, widely used and simple to implement constructors in Object Oriented Programming. The constructor is defined as public and get be called whenever a class is instantiated from external location of your program. Public Constructors is also known as default constructor of any class.

Also the Classes without a specified public constructor will have an implicit public constructor and maintained internally by CLR. Public constructor cannot be used in abstract class because public constructors always create instances of a type, and you cannot create instances of an abstract type.

using System;

class MyClass

{

// defalut public constructor

public MyClass()

{

System.Console.WriteLine("This is default constructor");

}

//public constructor with parameter

public MyClass(int a)

{

System.Console.WriteLine("Value is "+a);

}

}

class MyProgram

{

// start execution here from main method.

static void Main()

{

// initialize the class object

MyClass myclass1 = new MyClass(); // default constructor

MyClass myclass2 = new MyClass(5);

System.Console.ReadLine();

}

}

B. Protected Constructor: 

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.

Means protected constructor is used with an abstract class where object initialization could not happen (because of abtract nature). The base class initialization happen only when derived class is initialized and call base class constructor.

public class Base

{

protected Base() { }

protected static void staticFoo() { }

protected void instanceFoo() { }

}

public class Derived : Base

{

Derived()

: base() // initialize protected constructor through derived constructor

{ }

// start execution here from main method.

void Main()

{

Base b = new Base(); // Compiler Error: Can not access protected member

b.instanceFoo(); // Compiler Error: Can't call a protected instance method on a Base.

Base.staticFoo(); // You call protected static method

Derived d = new Derived();

d.instanceFoo(); // Can call an inherited protected instance method on a Derived

Derived.staticFoo(); // Can access static method of base class.

}

}


C. Private Constructor : 

Private constructor is a soul of Singleton pattern and used whenever we have to restrict the initializatio of class using 'new' keyword from outside world. The private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.

public class MyClass

{

private MyClass() { } // Private constructor

public static int iCount;

public static int IncrementCount()

{

return ++iCount;

}

}

class MyTestClass

{

// start execution here from main method.

static void Main()

{

MyClass myclass = new MyClass(); // Compiler Exception: Can't initialize class because of private constructor

MyClass.iCount = 100; // static variable directly accessible and initialized

MyClass.IncrementCount(); // Direct call to static method

System.Console.WriteLine("New value: {0}", MyClass.iCount);

}

}

Private constructor plays a very special role in singleton design pattern. Singleton class is same as static class and both are used relatively for similar purpose (to provide only one "instance") but still they have major difference.
1. Singletons class can implement interfaces or derive from useful base classes.
2. Singleton class object can be use as a parameter which is not possible for Static class.
3. Singletons can be handled polymorphically without forcing their users to assume that there is only one instance.

class Program

{

static void Main(string[] args)

{

// get the class object without initializing through 'new' keyword

MyClass instance = MyClass.Instance;

}

}

/// <summary>

/// Sealed class. Implemented through Singleton pattern.

/// </summary>

public sealed class MyClass

{

// The internal static valiable of class object

static readonly MyClass _instance = new MyClass();

/// <summary>

/// This is a private constructor, meaning no outsiders have access.

/// </summary>

private MyClass()

{

// initailize the internal variables

}

/// <summary>

/// The Instance object of an MyClass class.

/// Return the _instance object everytime whenever the MyClass class is initialized.

/// </summary>

public static MyClass Instance

{

get { return _instance; }

}

}

D. Static Constructor : 

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. 

It is called automatically before the first instance is created or any static members are referenced. Static Constructor is special in nature as a static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

A static constructor cannot be called directly and the user has no control on when the static constructor is executed in the program.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. The static constructors are basically useful when creating wrapper classes for unmanaged code.

class Program

{

static void Main(string[] args)

{

MyClass.foo(); // call the static member directly

MyClass myclass = new MyClass();

myclass.foo(10);

System.Console.ReadLine();

}

}

public class MyClass

{

static int a;

int b;

// Static constructor:

static MyClass()

{

a = 10; // initialize the static variable

//b = 20; // Compile Exception : non-static member can't be access through static constructor

System.Console.WriteLine("I am in static constructor");

}

// non-static constructor

public MyClass()

{

a = 10; // non-static constructor can initialize both static and non-static members

b = 20;

System.Console.WriteLine("I am in non-static constructor");

}

public static void foo()

{

System.Console.WriteLine("I am in static foo");

}

public void foo(int a)

{

System.Console.WriteLine("I am in non-static foo");

}

}

Something More

Constructor Overloading : A constructor with zero arguments is known as the default constructor. A constructor can take zero or more arguments as parameters. The program have multiple constructors in a class with different sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded constructors of a class must differ in their number of arguments, type of arguments, and/or order of arguments. This gives the user the ability to initialize the object in multiple ways.

The class in the program shown below contains three constructors. The first is the default constructor, followed by the two argument constructors. Note that the constructors differ in their signature.

using system;

public class MyClass

{

public MyClass()

{

//Default constructor

}

public MyClass(int sampleValue)

{

// This is the constructor with one parameter.

}

public MyClass(int firstValue, int secondValue)

{

// This is the constructor with two parameters.

}

}


Constructor Chaining : 

Constructor chaining refers to the ability of a class to call one constructor from another constructor. In order to call one constructor from another, we use base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether we want to call a constructor in the base class or in the current class.

using system;

public class MyClass

{

public MyClass(): this(10)

{

// This is the default constructor

// calling base class constructor and passing value 10 as parameter

}

public MyClass(int firstValue)

{

// This is the constructor with one parameter.

}

}


Conclusion


The best practice is to always explicitly specify the constructor, even if it is a public default constructor. Proper design of constructors goes a long way in solving the challenges faced in class designs. 
Page copy protected against web site content infringement by Copyscape

About the Author

Nakul.Lande
Full Name: Nakul Lande
Member Level: Bronze
Member Status: Member
Member Since: 7/24/2012 5:13:29 PM
Country: United States
Nakul Lande
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Niranjan44 on: 1/9/2013 | Points: 25

Login to post response

Comment using Facebook(Author doesn't get notification)