Constructor in C#

A constructor in C# is a special member of a class or struct that runs when an object is created. Its main job is to initialize the object so it starts in a valid state. Constructors are used everywhere in C# programs because most objects need some setup before they can be used safely.

When you write new Student() or new Product("Laptop", 55000), C# calls a constructor behind the scenes. Without constructors, objects would often be created with missing values, invalid state, or repeated setup code spread across the program.

A constructor has the same name as the class and does not have a return type. It can accept parameters, it can be overloaded, and it can call another constructor in the same class using the this keyword.


What Is Constructor in C#?

A constructor is a special method-like member that is automatically called during object creation. It initializes fields, properties, services, or any required data of the object.

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Student()
    {
        Name = "Unknown";
        Age = 18;
    }
}

Here, Student() is a constructor. When a new Student object is created, the constructor sets default values for Name and Age.

Rules of Constructor in C#

  • The constructor name must be the same as the class name.
  • A constructor does not have a return type, not even void.
  • A class can have multiple constructors with different parameters.
  • A constructor can use access modifiers such as public, private, protected, or internal.
  • A constructor runs automatically when an object is created using new.

Default Constructor in C#

A default constructor is a constructor with no parameters. If you do not write any constructor in a class, C# automatically provides a public parameterless constructor for that class.

class Car
{
    public string Brand { get; set; }
}

Car car = new Car();

This code works because the compiler provides a default constructor. But if you write your own parameterized constructor, the compiler will not automatically provide the parameterless one.

Parameterized Constructor in C#

A parameterized constructor accepts values from the caller and uses them to initialize the object. This is useful when an object should not exist without required data.

class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}

Product product = new Product("Keyboard", 1500);

The object is created with meaningful values immediately. This is better than creating an empty product and setting values later because the object is less likely to be used in an incomplete state.

Constructor Overloading in C#

Constructor overloading means creating multiple constructors in the same class with different parameter lists. This gives the caller different ways to create an object depending on how much information is available.

class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public Employee()
    {
        Name = "Not Assigned";
        Salary = 0;
    }

    public Employee(string name)
    {
        Name = name;
        Salary = 0;
    }

    public Employee(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }
}

Each constructor creates an Employee object, but with different available information. Constructor overloading is useful, but too many constructors can make a class confusing. If many combinations are needed, a factory method or options object may be cleaner.

Constructor Chaining with this Keyword

Constructor chaining allows one constructor to call another constructor in the same class. This avoids repeated initialization code and keeps the main setup logic in one place.

class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public Employee() : this("Not Assigned", 0)
    {
    }

    public Employee(string name) : this(name, 0)
    {
    }

    public Employee(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }
}

The final constructor contains the real initialization logic. The other constructors forward default values to it. This style reduces duplication and makes future changes safer.

Static Constructor in C#

A static constructor initializes static data of a class. It runs automatically before the class is used for the first time. A static constructor does not take parameters and does not use access modifiers.

class AppSettings
{
    public static string ApplicationName { get; private set; }

    static AppSettings()
    {
        ApplicationName = "NerdsDoStuff App";
    }
}

Static constructors are useful for initializing static configuration, lookup data, logging setup, or expensive shared values. They should be used carefully because they run automatically and can make startup behavior harder to trace.

Private Constructor in C#

A private constructor prevents outside code from creating objects directly. This is used in utility classes, singleton patterns, and classes that should only be created through controlled methods.

class MathHelper
{
    private MathHelper()
    {
    }

    public static int Square(int number)
    {
        return number * number;
    }
}

Since all members are static, there is no need to create an object of MathHelper. A private constructor blocks object creation from outside the class.

Constructor with Validation

Constructors are a good place to validate required values. If an object cannot work without valid data, the constructor should reject invalid input early. This prevents the program from carrying broken objects into later code.

class BankAccount
{
    public string AccountHolder { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string accountHolder, decimal openingBalance)
    {
        if (string.IsNullOrWhiteSpace(accountHolder))
        {
            throw new ArgumentException("Account holder is required");
        }

        if (openingBalance < 0)
        {
            throw new ArgumentException("Opening balance cannot be negative");
        }

        AccountHolder = accountHolder;
        Balance = openingBalance;
    }
}

This object cannot be created with an empty name or negative balance. That makes the rest of the program safer because a valid BankAccount object always follows the basic business rules.

Constructor and readonly Fields

Constructors are often used with readonly fields. A readonly field can be assigned during declaration or inside a constructor, but it cannot be changed later. This is useful for values that must stay fixed after object creation.

class ApiClient
{
    private readonly string baseUrl;

    public ApiClient(string baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    public void SendRequest()
    {
        Console.WriteLine($"Sending request to {baseUrl}");
    }
}

Once the object is created, baseUrl cannot be accidentally changed by another method in the class. This makes the class easier to reason about.

Constructor vs Method in C#

PointConstructorMethod
NameSame as class nameAny valid method name
Return TypeNo return typeHas return type or void
CallCalled automatically during object creationCalled manually
PurposeInitialize objectPerform behavior or calculation
OverloadingCan be overloadedCan be overloaded

The biggest difference is intent. A constructor prepares the object. A method performs an action after the object already exists. If code represents a normal operation, it should usually be a method, not constructor logic.

When Constructor Logic Becomes Too Much

A constructor should not do heavy work such as downloading files, sending emails, connecting to remote services, or running long calculations. Heavy constructor logic makes testing harder and makes object creation unpredictable. It is better to inject required dependencies through the constructor and run expensive work through a separate method.

Common Mistakes with Constructors

  • Writing a return type for a constructor.
  • Forgetting that a custom constructor removes the automatic parameterless constructor.
  • Putting too much heavy work inside a constructor.
  • Skipping validation for required constructor parameters.
  • Creating too many overloaded constructors with confusing combinations.
  • Using constructors for operations that should be normal methods.

A constructor should create a valid object, not run the entire application workflow. Expensive file access, network calls, database queries, or long processing tasks are usually better placed in methods or services.

Best Practices for Constructors in C#

  • Use constructors for required data.
  • Keep constructors short and predictable.
  • Validate required parameters immediately.
  • Use constructor chaining to avoid duplicate initialization code.
  • Use private constructors only when object creation must be restricted.
  • Prefer clear constructor parameters over unclear optional combinations.

Constructor Interview Points

For interviews and exams, remember that a constructor has the same name as the class and no return type. It runs automatically when an object is created. Constructors can be overloaded, but destructors cannot. Static constructors initialize static members and run once before first use. Private constructors restrict object creation from outside the class.

Also remember that constructors are not inherited like normal methods. A derived class constructor can call a base class constructor using the base keyword, but each class controls its own construction logic. This point becomes important when learning inheritance.

Constructor in Real Application Design

In real applications, constructors are often used for dependency injection. A service class may receive a logger, repository, configuration object, or API client through its constructor. This makes the dependency clear at object creation time and makes the class easier to test because fake dependencies can be passed during unit testing.

A constructor should make invalid object creation difficult. If a class needs a value to do its job, ask for that value in the constructor instead of allowing the object to exist half-ready. This simple habit improves reliability in large C# projects.

Good constructor design also improves readability. When another developer sees the constructor parameters, they immediately understand what the object requires before it can work correctly. That is much cleaner than creating an empty object and then setting many unrelated properties later.

This is why constructors are considered part of class design, not just syntax.

FAQs on Constructor in C#

Can a constructor return a value?

No. A constructor does not have a return type. Its purpose is to initialize the object during creation.

Can a class have multiple constructors?

Yes. A class can have multiple constructors as long as their parameter lists are different. This is called constructor overloading.

What happens if no constructor is written?

If no constructor is written, C# provides a default parameterless constructor for the class.

Can a constructor be private?

Yes. A private constructor is used when outside code should not create objects directly, such as in utility classes or controlled creation patterns.


Continue learning C# in order
Follow the topic sequence with the previous and next lesson.