Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Properties of a Constructor
3.
Types of Constructor
3.1.
Default Constructor
3.1.1.
Key points
3.2.
Parameterised Constructor
3.2.1.
Key Points
3.3.
Private Constructor
3.3.1.
Key Points
3.4.
Static Constructor
3.4.1.
Key Points
3.5.
Copy Constructor
3.5.1.
Key Points
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

C# Constructor

Author ANKIT KUMAR
3 upvotes
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A constructor is a special method of a class that is automatically invoked when an instance of the class is created. Constructors have exactly the same name as that of the class, and they do not have any return type, like functions. Constructors are primarily used to initialise the data members (variables) of a class while creating an instance of the class.

Example: 

using System;
class CodingNinjas {
    
    // default constructor which is not parameterised
    public CodingNinjas(){
        Console.WriteLine("Inside the constructor!");
    }
    
    // main method where the object is created
    static void Main() {
        
        // observe that we are not printing anything
        // still creating an object prints the message at the Console
        // this is because the call is made to the constructor
        
        CodingNinjas cn= new CodingNinjas();
    }
}

Output: 

Inside the constructor!

In the above example, we created an object named cn of the class CodingNinjas. Observe that after the new keyword, we write CodingNinjas() and not CodingNinjas. The CodingNinjas() (with braces) here makes a call to the constructor. Later in this article, we shall see how the constructors are used to initialise the data members.

Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable

Properties of a Constructor

The key features or properties of a constructor are:

  1. They have the same name as that of the class.
  2. They do not have any return type, like methods.
  3. We cannot create more than one static constructor inside a class and the static constructor created cannot be parameterised.
  4. There is no restriction to the number of constructors that can be created.
  5. Access modifiers are not mandatory while creating a constructor.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Constructor

There are five different types of constructors in C#. They are:

Default Constructor

A default constructor takes no parameters. Every instance of the class is initialised to the same values by a default constructor. Within a class, the default constructor sets all numeric fields to zero and all string and object fields to null.

Example:

using System;
class DefaultConstructor {
    
    // default constructor which is not parameterised
    // i.e.,  there is nothing inside ()
    public DefaultConstructor(){
        Console.WriteLine("Inside the default constructor!");
    }
    
    // main method where the object is created
    static void Main() {
        
        // default constructor is automatically called when the object is created
        DefaultConstructor cn= new DefaultConstructor();
    }
}

Output: 

Inside the default constructor!

Key points

  • It does not have any parameters.
  • Automatically called when an object is created.
  • No return type.

Parameterised Constructor

A parameterized constructor is one that has at least one parameter. The benefit of a parameterized constructor is that each instance of the class can be initialised with a different value. Inside the constructor braces(), there should be at least one parameter.

Example:

using System;
class ParameterisedConstructor{
    
    //data member which is not intialised currently
    string company;
    
    // Parameterised Constructor that takes a string value
    // and initialises the company field
    // we can also use "company" instead of "companyName" inside the braces
    
    public ParameterisedConstructor(string companyName){
        
        // using this operator we assign the value of companyName
        // inside the current object's company field
        this.company= companyName;
        
        Console.WriteLine("Inside the Parameterised Constructor\n");
    }
    static void Main() {
        
        // creating an object and passing a string value
        ParameterisedConstructor obj= new ParameterisedConstructor("Coding Ninjas");
        
        // using the object to print the data member's value
        Console.WriteLine("I work at : " +obj.company);
  }
}

Output:

Inside the Parameterised Constructor

I work at : Coding Ninjas

Key Points

  • It should have at least one parameter.
  • If we don't pass the value for the parameter while object creating it will throw a compile-time error.
  • It has no return type.

Private Constructor

A private constructor is created using a private specifier. It is not possible for other classes to derive from this class, nor can an instance of this class be created. They are typically used in classes with only static members. If a class has one or more private constructors and no public constructor is present in the class, other classes (except nested classes) cannot create instances of this class. 

Example:

using System;
class CodingNinjas {
    // private constructor
     private CodingNinjas(){
         
     }
        
     static void Main() {
    
    // below line will give error
    HelloWorld ob= new HelloWorld();
  }
}

Output: 

Compilation failed: 1 error(s), 0 warnings

Key Points

  • Mostly used when we only have static members.
  • It is an example of a singleton class pattern.
  • If the constructor is made private, instances of the class cannot be created.
  • No return type.

Static Constructor

When a constructor is created with the static keyword, it is invoked only once for all instances of the class, and it is invoked during the creation of the class's first instance or the first reference to a static member in the class. A static constructor is used to initialise the class's static fields and to write code that only needs to be executed once.

Example:

using System;
class CodingNinjas {
    
    // create a static constructor using the static keyword
    static CodingNinjas(){
        Console.WriteLine("Inside a static constructor!");
    }
    
    // public parameterised constructor
    public CodingNinjas(string name){
        Console.WriteLine("I work at : "+name);
    }
    
    // main method for object creation
    static void Main(){
        
        // create an object of the CodingNinjas class
        // observe that we do not leave the parameter empty.
        // we pass "Coding Ninjas" as the string value
        // It should have called only the second constructor
        // but output also includes the message from the first constructor
        CodingNinjas cn1= new CodingNinjas("Coding Ninjas");
        
        // this object does not invoke the static constructor
        // message inside the static constructor is not printed again
        // static constructor is invoked only once.
        CodingNinjas cn2= new CodingNinjas("Ninjas Coding");
    }
}

Output: 

Inside a static constructor!
I work at : Coding Ninjas
I work at : Ninjas Coding

Key Points

  • It does not have access modifiers.
  • It does not take any parameters.
  • It cannot be called directly.
  • It is invoked only once.
  • No return type.

Copy Constructor

A copy constructor is a constructor that creates an object by copying variables from another object. A copy constructor's purpose is to initialise a new instance with the values of an existing instance.

Example:

using System;
class CodingNinjas {
    
    // data members
    string course;
    string target;
    
    // the instance constructor
    public CodingNinjas(string course, string target){
        this.course = course;
        this.target = target;
    }
    
    // copy constructor
    // It takes a reference of the CodingNinjas class
    public CodingNinjas(CodingNinjas studentDetails){
        course = studentDetails.course;
        target = studentDetails.target;
    }
    
    // main method
    static void Main(){
        
        // first object cn1    
        CodingNinjas cn1 = new CodingNinjas("Data structures", "Interview preparation");
       
        // second object cn2
        // using copy constructor cn2 acquire the values from cn1
        CodingNinjas cn2 = new CodingNinjas(cn1);
       
        // use cn2 to print the values that were passed for cn1
        Console.WriteLine(cn2.course);
        Console.WriteLine(cn2.target);
    }
}

Output: 

Data structures
Interview preparation

Key Points

  • It creates an object by copying variables from another object.
  • Reference of the class is required as the parameter.
  • No return type.

FAQs

1.What are constructors in C#?

A constructor is a special method of a class that is automatically invoked when an instance of the class is created. Constructors have exactly the same name as that of the class, and they do not have any return type, like functions.

2. Why are constructors used?

Constructors are primarily used to initialise the data members (variables) of a class while creating an instance of the class.

3. What are the types of constructors available in C#?

There are five different types of constructors in C#. They are default constructor, parameterised constructor, private constructor, static constructor, copy constructor.

4. How do you identify a constructor?

They are like methods having the same name as that of the class and no return type.

Also Read About - singleton design pattern in c#

Key Takeaways

In this article, we discussed various types of constructors in C# and their code implementation in C#.

  • A constructor is a special method of a class that is automatically invoked when an instance of the class is created. 
  • They are like methods having the same name as that of the class and no return type.
  • There are five different types of constructors in C#. They are default constructor, parameterised constructor, private constructor, static constructor, copy constructor.

We hope that this blog has helped you enhance your knowledge regarding constructors in C# and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
C# Classes and Objects
Next article
Destructors in C#
Live masterclass