Constructors in C# with Examples

What is a Constructor in C#?

In C#, Constructors are special types of methods that get executed when an instance of the class or struct is created.

The main use of the constructor is to initialize and set the default values for the data members of the new object. It looks very similar to a method, but with no return type and have the same name as the class or struct.

A constructor is invoked when we use the new operator or the reflection (Example: Activator. CreateInstance) to create an object of a class.

If we forget to define the default constructor in a class, the compiler will automatically create one system-defined default constructor for that class.

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#:

    • The constructor name must be the same as the class or struct name.
    • A constructor doesn’t contain a return type, not even void.
    • A class can have any number of constructors, but only one static constructor.
    • A static constructor never overloads that’s why it doesn’t accept any parameter.
    • The static constructor doesn’t have any scope that’s why we can use any access modifier with static class.
    • A structure can have only parameterized constructors or a static constructor.
    • A class can have any type of constructors.
    • In C#, Constructor can’t be inherited.
    • Constructors can be overloaded.

Types of constructors in C#

In C# there are 5 types of constructors available.

Default Constructor in C#

A constructor with no parameters is called a default constructor or parameterless constructor.

    • The default constructor is invoked when we create an object of the class by using the “new” operator.
    • A default constructor initializes every instance of the class with the same values.
    • It can be used to set initial values for the fields, zero for the numeric and null for the string and object in a class.
    • If we don’t specify any constructors at all, a default constructor is provided by the compiler.

Types of default constructor in C#

In C#, A default constructor is classified into two types.

    • System-defined
    • User-defined

System-defined: If we forget to define any constructor explicitly in the class, then the compiler will automatically create a default constructor for that class at the compile time.

This constructor is called system-defined constructor and it will assign the default values to all the instance members of the class.

User-defined: A parameterless constructor that is defined explicitly by the user is called a user-defined default constructor.
This constructor does not accept any parameter, but it allows us to write the business logic in its body.

Examples of default constructor in C#

Example 1:

using System;
namespace DefaultConstructor
{  
    //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.

In the above result, we can see that the default constructor gets executed automatically after creating an instance of the “User” class and initialized the fields.

Example 2:

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 and null for the string
        }
    }
    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: 0 Name:
}

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

Parameterized Constructor in C#

In C#, A constructor with at least one parameter is called a parameterized constructor.
The parameterized constructor helps us to assign an initial value to an object at the time of its creation.
It gives us the provision to initialize each instance of the class with a different value.

Examples of the parameterized constructor in C#

Example 1:

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 above example, we can see that a parameterized constructor allows us to initialize each instance of the class with different values dynamically.

Static Constructor in C#

A static constructor is a special kind of constructor that invokes automatically before the first instance of a class is created.
It is used to initialize only static data members of the class or to write the code that needs to be executed only once throughout the execution of the program static constructor  static constructor  

The purpose of using a static constructor is to trigger a piece of code automatically without creating an object of a class.

Characteristic of static constructor:

    • A static constructor doesn’t take any access modifiers or input parameters.
    • A static constructor is invoked automatically to initialize the class before the first instance of a class is created or any static members are referenced.
    • The static constructor gets invoked even before the Main() method.
    • The user has no control over when the static constructor is executed in the program.
      A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
    • 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.

Conclusion:

In this article, I have explained in details about the different types of constructor available in C#. I hope you enjoyed this post. If you have any questions, please post your questions in the comment section.

Thanks for visiting 🙂

Leave a Reply