Constructor in C# | Types of constructors in C# with Examples

Constructor in CSharp
Constructor in C#

What is a Constructor in C#?

A Constructor in C# is a special method that get executed when an instance of the class or struct is created. The constructor is used to initialise and set default values for the data members of the new object. It has the same name as the class or struct.

If we create a class that doesn’t have a constructor, the compiler will automatically create one default constructor for that class. Each class must have at least one constructor.

The default constructor is used to initialize all the numeric fields/variables in a class to zero, and all the string fields and object to null.

C# Constructor Syntax

Following is the syntax to create a constructor in C#

image constructor syntax in c#
constructor syntax

In the above example, we have created constructor User with the same name as class or struct.

Characteristic of constructor in C#

    1. The name of the constructor must be the same as the name of the class or struct in which it is defined.
    2. A constructor doesn’t contain a return type, not even void.
    3. In a class, there can be any number of constructors, but only one static constructor.
    4. Constructors can be overloaded (except static constructor).
    5. The static constructor doesn’t have any scope that’s why we can use any access modifier with static class.
    6. A structure can have only parameterized constructors or a static constructor.
    7. In C#, Constructor can’t be inherited.

Types of constructors in C#

In C# there are 5 types of constructors available.

1. Default Constructor in C#

A constructor without any parameters is called a default constructor. The default constructor is used to specify the code that is executed when you create a new instance of a type with the new operator.

    • A default constructor can be used to specify initial values for fields and variables in a class, such as zero for numeric fields and null for string and object fields.
    • A default constructor initializes every instance of the class with the same values.
    • If you don’t specify any constructors in the class, the compiler will automatically provide a default constructor for that class.

Examples 1: Default constructor in C#

The following is the example of the default constructor.

using System;
namespace DefaultConstructorExample
{  
    // User Class
    public class User
    {
        // Fields
        public int userId;
        public string userName;

        // Default Constructor
        public User()
        { 
            this.userId = 10;
            this.userName = "Shekh Ali";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {   
            // This will invoke default constructor
            User user = new User();
            Console.WriteLine($"Id: {user.userId} Name: {user.userName}");
        
            Console.ReadLine();
        } 
    }
    // Output:
    // Id: 10 Name: Shekh Ali
}

The output of the above default constructor program:
The output of the above C# program.

As shown in the above program result, the default constructor is executed automatically after creating an instance of the User class.

Example 2: Default Constructor sets initial values to the fields

using System;
namespace DefaultConstructor
{  
    // Class
    public class User
    {
        // Fields
        public int userId;
        public string userName;

        //Default Constructor
        public User()
        {
            // Default constructor will initilize
            // zero for the numeric fields and null for the string field
        }
    }
    class Program
    {
        static void Main(string[] args)
        {   
            // Object is created, default constructor is called
            User user = new User();
            Console.WriteLine($"Id: {user.userId} Name: {user.userName}");
        
            Console.ReadLine();
        } 
    }
    // Output:
    // Id: 0 Name:
}

Default constructor result2
The default constructor initializes zero for the numeric and null for the string or object.

2. Parameterized Constructor in C#

A constructor with at least one parameter is called a parameterized constructor. The parameterized constructor allows us to provide an object’s initial values when it is created. It allows us to give each instance of the class different values during object creation.

Example: Parameterized constructor in C#

The following is the example of parameterized constructor in C#.

using System;
namespace ParameterizeConstructor
{  
    // Class
    public class User
    {
        // Fields
        public int userId;
        public string userName;

        // Parameterize Constructor
        public User(int id, string name)
        {
            this.userId = id;
            this.userName = name;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // This will invoke Parameterized constructor
            User user1 = new User(101,"Shekh Ali");
            User user2 = new User(102, "Klara konikova");

            Console.WriteLine($"Id: {user1.userId} Name: {user1.userName}");
            Console.WriteLine($"Id: {user2.userId} Name: {user2.userName}");

            Console.ReadLine();
        } 
    }
    // Output:
    // Id: 101 Name: Shekh Ali
    // Id: 102 Name: Klara konikova
}
Parameterized constructor result:
Result: Different values for the different instances of the class.

In the example above, We can see how a parameterized constructor allows us to dynamically initialize each instance of the class with different values.

3. Static Constructor in C#

A static constructor is a special constructor that is called automatically before the first instance of a class is created.
It’s used to only initialize the class’s static data members or to write code that only has to be run once during the program’s execution. static constructor  static constructor  

The objective of utilizing a static constructor is to automatically trigger a piece of code without having to create a class instance.

Learn more about static constructor: Static constructor in C# with examples

Characteristic of static constructor:

    • A static constructor doesn’t take input parameters.
    • A static constructor does not have any access modifiers.
    • A static constructor is executed automatically before the first instance of a class is created or any static data members are referenced.
    • The static constructor gets invoked even before the Main() method.
    • A static constructor is independent of an object because it calls automatically by the CLR, not by the developer.
    • In C#, a class or struct can have only one static constructor.

Example of the static constructor.

Following is the example of a static constructor in C#.

using System;

namespace StaticConstructorExample
{
    public class Person
    {
        static Person()
        {
            Console.WriteLine(" Static Constructor Invoked !");
        }

        public Person()
        {
            Console.WriteLine(" Default Constructor Invoked !");
        }

    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Person person = new Person();       
        }
    }
}
Static constructor example csharp
Static constructor example

Note: The Static constructor usually runs before instance constructors.

4. Private Constructor

Private Constructor in C# is a special instance constructor that is commonly used in classes with only static members. If a class has one or more private constructors but no public constructors, other classes, except nested classes, are not allowed to make instances of that class.

please visit my previous blog to learn more about the private constructor in c#

Characteristics of the Private Constructor:

    • Use the private constructor when a class contains only static members.
    • Private constructor in C# can be used to create a Singleton class.
    • A class having private constructor cannot inherited by the other classes.
    • It is not possible to create instances a class that has one or more private constructors but no public constructors.

Private constructor example

using System;

namespace PrivateConstructorExample
{
    public class Person
    {
        public string name;

        private Person()
        {
            Console.WriteLine(" Private Constructor Invoked !");
        }

        public Person(string name)
        {
            this.name = name;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            // it will generate an error because the constructor is inaccessible due to its protection level
            // Person person = new Person(); 

            // this will works fine
            Person person = new Person("Shekh Ali");
            Console.WriteLine($" Name : {person.name}");
        }
    }
    // Output:
    //  Name : Shekh Ali
}

5. Copy Constructor

In C#, The Copy constructor is a constructor that creates an object by cloning data from one object to another. It can be used to copy data from an existing object to a new object without changing the value of the existing object. The copy constructor is a parameterized constructor that accepts objects of the same type as parameters.

please visit my previous blog to learn more about the Copy Constructor in C#

Syntax:

// Class
 public class User
 {
     // Parameterized Constructor
     public User(int id, string name)
     {
                
     }
 
     // Copy constructor
    public User(User previousUser)
     {
        //Business logic code
     }
 }

Example of Copy constructor in C#

using System;
namespace CopyConstructor
{  // C# program demonstrating how to use the  copy constructor
    
   // User class
    public class User
    {
        //Instance variables
        public int Id;
        public string Name;
 
        // Parameterized Constructor
        public User(int id, string name)
        {
            this.Id = id;
            this.Name = name;                
        }
 
        // Copy Constructor
       public User(User previousUser)
        {
            this.Id = previousUser.Id;
            this.Name = previousUser.Name;       
        }
 
        // Print person details
        public void PrintDetail()
        {
          Console.WriteLine($"Id: {Id} Name: {Name}");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
 
       // This will invoke instance constructor
            User user1 = new User(10,"Shekh Ali");
 
       // This will invoke copy constructor
       // Creating another User object by copying user1
            User user2 = new User(user1);
 
       // Change user2 Id and Name
            user2.Id = 20;
            user2.Name = "Robert";
 
       // Print detail of user to verify that the 
       // Id and Name fields are unique.

            user1.PrintDetail();
            user2.PrintDetail();

            Console.ReadLine();
        } 
    }
    /* Output:
     Id: 10 Name: Shekh Ali
     Id: 20 Name: Robert
 
     */
}

C# copy constructor rules

    • The copy constructor in C# must have the same name as the name of the class or structure.
    • It does not contain a return type, not even void.
    • The copy constructor cannot be inherited in C#.
    • It cannot be static.
    • A class can have multiple constructors in order to create a copy constructor.
    • Its main purpose is to initialize a new instance with the value of an existing instance.

Thank you for taking the time to read the blog, if you find it interesting, please like, comment, and share it with others. Thanks.

Articles to Check Out

Leave a Comment