.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Defining Constructors and its types

Posted By:Gaurav Arora       Posted Date: April 28, 2009    Points: 25    Category: C#    URL: http://www.dotnetspark.com  
 

Definition:

In simple terms, Constructor is a special kind of method with class name as method name and gets executed when its (class) object is created.

This article will give you a detailed explanation on C# constructors and its types.

Now, when we look at the above definition in a broader sense, a constructor is a class method that gets automatically executed whenever class's object is created or whenever class is initialized.

 

Consider following bit of code:

public class MsDotNetHeaven

    {

        public MsDotNetHeaven()

         {

              //A default Constructor

         }

 

      //Class members

 

    }

 

In the above snippet, the method MsDotNetHeaven() is called the constructor of class MsDotNetHeaven, also called default constructor.

 

Behind the scenes

What happened behind the scenes : whenever you try to create an object of class or initialize a class, then the default constructor will be automatically invoked.

//Initializes the Class 

MsDotNetHeaven objMsDnH = new MsDotNetHeaven();

 

Types of Constructor

It can be always debated, but I always like to segregate constructors by following types:

 

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.

 

Parameterized Constructor

At times, we will require initializing class members during instantiation and this is the time where parameterized constructor will come into picture. It follows the same rules as default constructor and will have parameters. Go through following snippet:

 

public class MsDotNetHeaven

    {

        public MsDotNetHeaven()

         {

              //A default Constructor

         }

 

        public MsDotNetHeaven(String strName)

         {

              //A parameterized Constructor having one parameter

         }

       

  public MsDotNetHeaven(String strFirstName, String strLastName)

         {

              //A parameterized Constructor having two parameters

         }

 

      

      //Class members

 

    }

 

Note:

1.      A default constructor should be explicitly declared while declaring parameterized constructor.

2.      Some writer also take Private constructor and Static Constructor as types of constructor but in my view these are constructor with different modifiers so behave differ; I will cover these in next section.

 

Access Modifiers and Prefix with Constructors

By default, Constructors are public but we can also use other modifiers and prefix like private and static. With the use of these modifiers constructors behave differently:

Using Access Modifier private with Constructor

When we decorate a constructor as private then it is called as private Constructor.

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.

Sometimes, there will be a need where we should not allow outer world to instantiate by default. To achieve this, we need to use private access modifier with the constructor. Consider following piece of code:

public class MsDotNetHeaven

    {

        private MsDotNetHeaven()

         {

              //A default Constructor as private

         }

 

      //Class members

 

    }

 

Now whenever you try to invoke following piece of code,

//Initializes the Class 

MsDotNetHeaven objMsDnH = new MsDotNetHeaven();

 

It will throw an error: Constructors. MsDotNetHeaven. MsDotNetHeaven ()' is inaccessible due to its protection level

 

We can instantiate the above class by declaring another public constructor that has parameters. Refer the below code,

public class MsDotNetHeaven

    {

        private MsDotNetHeaven()

         {

              //A default Constructor as private

         }

        public MsDotNetHeaven(String strName): this()

         {

              //A parameterized Constructor having one parameter

              System.Console.WriteLine("My name is : " + strName);

         }

       

  //Class members

    }

 

Now, you can initialize class as follow:

 

//Initializes the Class 

MsDotNetHeaven objMsDnH = new MsDotNetHeaven("Gaurav Arora");

 

Using prefix static with Constructor

When we decorate a constructor as static, then it will become a static constructor.

For C++ developers it's a new concept introduced in C#.

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.

Consider the following:

 

public class MsDotNetHeaven

    {

        static MsDotNetHeaven()

         {

              //A static Constructor

           // Can only access static members here.

 

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

         }

 

      //Class members

 

    }

 

Now, when you create an instance of the class MsDotNetHeaven, the line "I am a static constructor" is printed.

Consider following piece of code,

 

public class MsDotNetHeaven

    {

        static MsDotNetHeaven()

         {

              //A static Constructor

           // Can only access static members here.

 

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

         }

 

        public MsDotNetHeaven()

         {

              //A default Constructor

         }

 

      //Class members

 

    }

 

Above code is perfectly alright and will perform same result as earlier code.

 

Calling Parent Class Constructors in child class during inheritance

Suppose a scenario, you want to call the Parent class constructor then from the child class. How?

It's Simple!! It can be achieved by using base()

Consider following code-snippet

 

 

public class MsDotNetHeaven

{

        public MsDotNetHeaven()

         {

              //A default Constructor

         }

 

        public MsDotNetHeaven(String strName)

         {

              //A parameterized Constructor having one parameter

         }

       

     //Class members

 

}

 

public class MsDotNetMentor : MsDotNetHeaven

{

        public MsDotNetMentor ()

         {

              //A default Constructor

         }

 

        public MsDotNetMentor (String strName) : base(strName)

         {

              //A parameterized Constructor having one parameter

         }

       

     //Class members

 

static void Main()

    {

       MsDotNetMentor objMsDnM = new MsDotNetMentor(); //(A)

    MsDotNetMentor objNameMsDnM = new MsDotNetMentor("Gaurav Arora"); //(B)

    }

 

 

}

 

1.    From above : the sequence of invoking a constructor is first public MsDotNetHeaven() and then public MsDotNetMentor()

2.    From above : the sequence of invoking a constructor is public MsDotNetHeaven(String strName)and then public MsDotNetMentor(String strName)

 

Note

Ø       A static constructor should not be declared with any access modifier.

Ø       A static constructor does not accept parameters

Ø       A static constructor is called automatically.

Ø       There is no way to call a static constructor directly.

Ø       Can't stop the execution of Static constructor

 

Points to Remember

Ø       Constructor is nothing but a special method, which initializes the class or its task to initialize the object of it class.

Ø       Its name must be same as the name of class

Ø       This is a special method as constructors do not have return types, not even void

Ø       Constructor cannot return any value because they didn't have any return type.

Ø       Constructor can't be get inherited, although a derived class can class the base class constructor.

Ø       A class has atleast one constructor also known as default constructor [a constructor without parameter]

Ø       You have to explicitly write a default constructor while overloading constructors.

Ø       Concept declaring multiple constructors of a class with different sets of parameters known as Constructor overloading.

Ø       A constructor can be called another constructor using this()

 

Conclusion

Constructor is one of the important concepts in object oriented world and one should know how it can be used for in different type of scenarios. Thus, this article is aimed to provide some detailed explanation about the same

 


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend