In this blog, I will explain what is the constructor in c# with example and types of constructors in c#. Constructors have a very special meaning to Compiler and CLR but sometimes its flow seems difficult for a developer. And that point, generally constructor name should be same as class name. If we want to create a constructor in a class we need to create a constructor method name same as class name.

What is Constructor?

A constructor is a special type of method of a class which will invoke automatically whenever we create object or instance of a class. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create a one default constructor for that class. There is always at least one constructor in every class.

Some of the main points regarding the Constructor are:

  • A constructor is a special member function because generally, constructor name and class name both are same.
  • It will call automatically when we create an object of the class.
  • A constructor doesn’t have any return type and we don’t write void keyword also.
  • If we create a class without constructor then compiler automatically add the default constructor for that class.
  • A class can have any number of constructors.
  • A class can have only one default constructor.
  • A Static constructor can’t be a parameterized constructor.
  • We can use only one static constructor within a class.
  • We can define Multiple overloads of constructor.

Syntax of a Constructor:

The following code show how to declare class constructor by using the same name without any return type.

class Sample 
    { 
        public Sample() 
        { 
            //Code goes here 
        } 
    }

Types of Constructor:

There are different types of constructors you can write in a class –

  • Default constructor
  • Parameterized constructor
  • Copy constructor
  • Static constructor
  • Private constructor

Now let’s explain each in detail.

Default constructor:

  • Default constructor doesn’t take any type of parameters.
  • It is automatically removed by the compiler when we add a new explicit constructor.
  • A constructor doesn’t have any parameters as well as any internal logic.

Let’s see the example of Default Constructor

using System; 
namespace SampleAppConstructor  
{ 
    public class Person 
    { 
        public string name, age; 
        public Person() // Default Constructor 
        { 
            name = "pawan kumar"; 
            age = "25"; 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Person obj = new Person(); //an object is created,constructor is called 
            Console.WriteLine("My name is " + obj.name); 
            Console.WriteLine("My age is " + obj.age); 
            Console.ReadKey(); 
        } 
    } 
}

After run above program it will show output like as shown below,

 Default Constructor

Parameterized constructor:

  • There should at least one parameter in a parameterized constructor.
  • A class can have multiple parameterized constructors.Then parameter types or the number of parameters should be separate in each parameterized constructors.
  • Parameterized constructor advantage is that you can initialize each instance of the class to various values.
  • Parameterized Constructors can exist even without the existence of Default Constructor.

Let’s see the example of Parameterized Constructor

using System; 
namespace SampleAppConstructor  
{ 
    public class Person 
    { 
        public string name, age; 
        public Person(string x, string y) // decalaring Paremetrized Constructor with x,y parameter 
        { 
            name = x; 
            age = y; 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Person obj = new Person("pawan kumar", "25"); // Creating object of Parameterized Constructor 
            Console.WriteLine("My name is " + obj.name); 
            Console.WriteLine("My age is " + obj.age); 
            Console.ReadKey(); 
        } 
    } 
}

After run above program it will show output like as shown below,

 Parameterized Constructor

Copy constructor:

  • Copy constructor a constructor which creates an object by copying variables from another object.
  • A constructor is used to initialize a new instance to the values of an existing instance.

Let’s see the example of Copy Constructor 

using System;  
namespace SampleAppConstructor 
{ 
    public class Person 
    { 
        public string name, age; 
        public Person(string x, string y) // Instance constructor 
        { 
            name = x; 
            age = y; 
        } 
        public Person(Person obj) // declaring Copy constructor 
        { 
            name = obj.name; 
            age = obj.age; 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Person obj = new Person("pawan kumar", "25");// Create a new Person object. 
            Person objPerson = new Person(obj); // here is obj details is copied to objPerson. 
            Console.WriteLine("My name is " + objPerson.name); 
            Console.WriteLine("My age is " + objPerson.age); 
            Console.ReadKey(); 
        } 
    } 
}

After run above program it will show output like as shown below,

 Copy Constructor

Static constructor:

  • There should be no access modifier with the static constructor.
  • A static constructor can only access the static data fields of the class.
  • Static constructor will not accept any parameters since it is automatically called by CLR.
  • It is just called once while creation of the primary instance of the class. After that, no instance of a class will call the static constructor.
  • We can declare only one static constructor in a class.

Let’s see the example of Static Constructor

using System;   
namespace SampleAppConstructor  
{ 
    public class Sample 
    { 
        public Sample() 
        { 
            Console.WriteLine("Instance Constructor"); 
        }     
        static Sample() 
        { 
            Console.WriteLine("Static Constructor"); 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            //Static Constructor and instance constructor, both are invoked for first instance 
            Sample obj = new Sample(); 
            //Only instance constructor is invoked 
            Sample objSample = new Sample(); 
            Console.ReadKey(); 
        } 
    } 
}

After run above program it will show output like as shown below,

 Static Constructor

Private constructor:

  • The private constructor is generally used in classes that contain static members only.
  • If the class only has private constructors then we can neither create the object of the class nor it can be inherited by other class.
  • A Private constructor is a special instance constructor.
  • If we want to make an object of the class having a private constructor. We can have a set of public constructor along with the private constructor of the class.
  • We can create private constructors and public constructors in a single class with different signatures.
  • Microsoft recommends its uses to implement Singleton Pattern.

Let’s see the example of Private Constructor

using System; 
namespace SampleAppConstructor 
{ 
    public class Sample 
    { 
        public string name, age; 
        public Sample(string x, string y) 
        { 
            name = x; 
            age = y; 
        } 
        private Sample()  // Private Constructor Declaration 
        { 
            Console.WriteLine("Private Constructor"); 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Here we don't have chance to create instace for private constructor 
            Sample obj = new Sample("pawan kumar", "25"); 
            Console.WriteLine("My name is " + obj.name); 
            Console.WriteLine("My age is " + obj.age); 
            // it will not work because of inaccessability 
            //Sample obj = new Sample(); 
            Console.ReadKey(); 
        } 
    } 
}

After run above program it will show output like as shown below,

 Private Constructor

Main Use of private constructor in C#:

Following are the situations when we can make use of the private constructor.

1) Stop object creation of a class

In this case, if we want to stop object creation of a class, then we can make the class constructor private. In this way, if we try to create an object from the main program or other classes, then the compiler will flash an error.

   class TestA 
    { 
        //private constructor 
        private TestA() 
        { 
        } 
    } 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            TestA obj = new TestA();//Error cannot access private constructor 
        } 
    }

2) Use in Singleton class

We realize that singleton class allows the only single instance of it all through the execution of the application. When we plan a singleton class, we use a private constructor. In this way, no user can make an object of this class to stop multiple object creation. And, the singleton class itself provides the same object over and over on demand.

In the below example, we have shown that how to use a private constructor with Singleton class.

 public class SingletonSample 
 { 
     private static SingletonSample instance = null; 
     private SingletonSample() { } 

   public static SingletonSample getInstance()  
     { 
         if (instance == null) 
             instance = new SingletonSample(); 
         return instance; 
     } 
 } 
 class Program 
 { 
     static void Main(string[] args) 
     { 
         SingletonSample.getInstance(); 
         Console.ReadKey(); 
     }
 }

Conclusion

A constructor is the very first method called whenever we create the instance of a class. Each type of constructor has its unique capabilities and uses. I hope this blog will help you a lot to understand about of a constructor.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here