Understanding C# Constructors

No.of Views971
Bookmarked0 times
Downloads 
Votes0
By  Vishal Nayan   On  28 Apr 2011 08:04:22
Tag : CSharp , Miscellaneous
Constructor is a special kind of method which have name same as that of class they belong and gets executed when its (class) object is created.In other words a constructor is a class default method that gets automatically executed whenever class’s object is created or whenever class is initialized.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Constructor is a special kind of method which have name same as that of class they belong and gets executed when its (class) object is created.In other words a constructor is a class default method that gets automatically executed whenever class’s object is created or whenever class is initialized.

Consider this example

public class demo
    {
        public demo ()
         {
              //A default Constructor
         }
 
      //Class members
 
    }

In this example, the method demo() is called the constructor of class demo, also called default constructor.

How it works: whenever you try to create an object of class or initialize a class, then the default constructor will be automatically invoked.

//Initializes the Class 
demo object = new demo ();

Tips to remember about constructor

1)    Constructor can’t be inherited, although a derived class can class the base class constructor.
2)    You have to explicitly write a default constructor while overloading constructors.
3)    Concept declaring multiple constructors of a class with different sets of parameters known as Constructor overloading.
4)    A constructor can be called another constructor using this()

Types of Constructor

1)    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.
2)    Parameterized constructor: when we initialize class members during instantiation we use parameterized constructor which is similar to default constructor butl have parameters.

Below is code example:

public class demo
    {
        public demo()
         {
              //A default Constructor
         }
 
        public demo(String Name)
         {
              //A parameterized Constructor having one parameter
         }
       
  public demo(String FirstName, String LastName)
         {
              //A parameterized Constructor having two parameters
         } 
      
      //Class members
 
    }

When you create a parameterized constructor, we need to declare a default constructor explicitly.

Access modifier for constructor

1)    Public constructor: Constructors are public by default.
2)    Private constructor: It 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 demo
    {
        private demo()
         {
              //A default Constructor as private
         }  
    }

So when we will try to create object of this class, it will generate an error.

i.e:

demo object = new demo () //Error 

Is there any way to create object of this class.

We can instantiate the above class by declaring another public constructor that has parameters.

public class demo
    {
        private demo()
         {
              //A default Constructor as private
         }
        public demo(String strName): this()
         {
              System.Console.WriteLine(“Hello Mr. : “ + strName);
         }
       
  //Class members
    }

And now you can initialize object for this class,

demo object = new demo() , which will work fine.

3)    Static Constructor: A static constructor is used to initialize any static data, or to perform a action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.

public class demo
    {
        static demo()
         {
           //A static Constructor
           // Can only access static members here.
 
              System.Console.WriteLine("I am a static constructor.");
         } 
    }

So when we create object of this class, “I am a static constructor” gets printed.
Examine the below code as well,
 

public class demo
    {
        static demo()
         {
            //A static Constructor
           // Can only access static members here.
 
              System.Console.WriteLine("I am a static constructor.");
         }
 
        public demo()
         {
              //A default Constructor
         }
 
      //Class members
 
    }

This example also prints the same result, “I am a static constructor”

Point to remember about static constructor:

1) A static constructor should not be declared with any access modifier.
2) A static constructor does not accept parameters
3) A static constructor is called automatically.
4) There is no way to call a static constructor directly.

How to call parent class constructor in derived class during inheritance

It can be achieved by using base ()

Example:

public class parent
{
        public parent ()
         {
              //A default Constructor
         }
 
        public parent (String strName)
         {
              //A parameterized Constructor having one parameter
         }
       
     //Class members
 
}
 
public class child : parent
{
        public child ()
         {
              //A default Constructor
         }
 
        public child (String strName) : base(strName)
         {
              //A parameterized Constructor having one parameter
         }
       
     //Class members
 
static void Main()
    {
      child object1 = new child (); //1*
      child object2 = new child (“Vishal Nayan”); //2*
    }
 
 
}

Note:Sequence is important here in which constructor is called.

1)    First parent class public constructor, parent() is called then child class public constructor, child()
2)    First parent (String strName) and then child (String strName).

That's all. hope help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top