Constructors in C#: A Comprehensive Guide with Code Examples

A constructor in C# is a special method used to initialize an object when it is created. It is called automatically when an object is instantiated, and its main purpose is to ensure that the object is in a valid state before it is used. Constructors have the same name as the class they belong to and do not have a return type.

This article will explore what constructors are, how they work, and how to use them in your C# programs.

Constructors in C#
Constructors in C#

What are Constructors in C#?

In C#, a constructor is a special method that runs automatically whenever a new object of a class is created. Its purpose is to initialize the class’s data members and ensure that all required values are assigned.

The constructor has the same name as the class and no return type, not even void.
If you don’t define a constructor for a class in C#, the compiler automatically generates a default constructor for that class.

Example:

The following is an example to create constructors in C#:

image constructor syntax in c#
Constructors in C#

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

Types of Constructors in C#

There are 5 Types of Constructors in C#:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

01. Default Constructor

A default constructor is a constructor that takes no parameters and is automatically generated by the compiler if no other constructors are defined.
It is used to initialize a class’s fields or variables with default values, such as assigning zero to numeric fields and null to a string or object.

Example: Default Constructor in C#

// class
public class Employee 
{
    public Employee() 
	{
        // default constructor
    }
}

02. Parameterized Constructor

A parameterized constructor is a constructor that takes one or more parameters.
It allows you to initialize the object with specific values when it is created.

A parameterized constructor has at least one parameter and allows you to set different values for each instance of the class

Example: Parameterized constructor

Here is an example of a parameterized constructor in C#:

public class Employee {
    public string Name { get; set; }
    public int Age { get; set; }
   // parameterized constructor 
    public Employee(string name, int age) {
        Name = name;
        Age = age;
    }
}

03. Copy Constructor

  • The copy constructor creates an object by copying variables from another object. Its primary purpose is to create a new object with the same values as an existing object.
  • It is a type of parameterized constructor that takes an object of the same class as its input parameter.

Example: Copy Constructor

Here is an example of a copy constructor in C#:

using System;
namespace CopyConstructor
{  
   // 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
     */
}

04. Static Constructor

In C#, a static constructor is a special type of constructor used to initialise static data members of a class. It is called automatically by the runtime when the class is first used, either by creating an instance of the class or accessing a static member of the class.

The syntax for a static constructor is similar to that of a normal constructor, but it uses the “static” keyword before the constructor name. A static constructor has no access modifiers and cannot take any parameters.

Here are a few scenarios where you might use a static constructor:

  1. Initializing static variables: If you have static variables in your class that need to be initialized using some complex calculation or external resource, you can use a static constructor to perform the initialization when the class is first used.
  2. Registering event handlers: If your class needs to register event handlers, that should only be done once for the entire application, you can use a static constructor to perform the registration when the class is first used.
  3. Initializing other static objects: If your class depends on other static objects that need to be initialized in a particular order, you can use a static constructor to ensure that the objects are initialized before the class is used.
  4. One-time setup tasks: If your class needs to perform one-time setup tasks, such as setting up a database connection or initializing a logging framework, you can use a static constructor to perform the tasks when the class is first used.
  5. Lazy initialization: If you want to defer the initialization of a static variable until it is actually needed, you can use a static constructor to perform the initialization the first time the variable is accessed.

In general, static constructors are useful when performing some initialization or setup tasks for a class that should only be done once for the entire application.

Example: Static Constructor

Here is an example of a static constructor in C#:

public class MyClass
{
    static int staticValue;
    // static constructor
    static MyClass()
    {
        staticValue = 42;
    }
    // Other members of the class
}

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

05. Private Constructor

A private constructor in C# is typically used to prevent class instances from being created outside of the class itself. It can be useful in situations where you want to control how objects of the class are created and ensure that they are created in a specific way.

For example, you might use a private constructor in a Singleton pattern where only one instance of the class is allowed. By making the constructor private, you prevent other code from creating new instances of the class and ensure that only the Singleton instance is used.

Example: Private Constructor

Here is an example of a private constructor in C#:

public class Singleton {
    private static Singleton _instance;

    private Singleton() {
        // private constructor
    }

    public static Singleton GetInstance() {
        if (_instance == null) {
            _instance = new Singleton();
        }
        return _instance;
    }
}

Characteristics Of Constructors in C#

CharacteristicDescription
Purpose:Constructors are used to initializing objects when they are created and ensure that all necessary values are set.
Identity: Constructors have the same name as the class name.
Return Type:Constructors cannot have a return type, including void.
Parameter:Constructors can have parameters, allowing developers to initialize objects with specific values.
Default Constructor:C# provides default constructors, which are called automatically if no constructor is defined in the class.
Overloaded Constructors:Constructors can be overloaded, which means that a class can have multiple constructors with different parameters.
Reusability:Constructors can be reused by chaining them, allowing you to reuse code and avoid repeating the same initialization logic.
This keyword:Constructors can call other constructors using the “this” keyword.
Accessibility:Constructors are implicitly called when an object is created and cannot be called explicitly.

FAQs

Q: What is a constructor in C#?

A constructor in C# is a special method that is used to initialize the state of an object and ensure that all necessary values are set.

Q: How many constructors can a class have in C#?

A class can have multiple constructors with different parameters, which is known as overloaded constructors.

Q: Can you reuse code in constructors in C#?

Yes, you can use constructor chaining to reuse code and avoid repeating the same initialization logic in multiple constructors.

Q: What is a private constructor in C#?

A private constructor is a constructor that can only be called within the same class. It is used in situations where a class should not be instantiated directly, such as in the Singleton pattern.

References: Constructors in C#

Articles you might also like:

We would love to hear your thoughts on this post. Please leave a comment below and share it with others.

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments