Constructors in C#
A constructor is a special member of a class that is automatically called when an object of that class is created. Constructors are mainly used to initialize the object with appropriate values.
In simple words, a constructor helps us prepare an object when it is created. It can assign initial values to properties and perform initialization work required by the object.
What is a Constructor?
A constructor is a special method-like member of a class that has the same name as the class. It does not have a return type, not even void.
Consider the following example:
public Student()
{
Console.WriteLine( "Student object created.");
}
}
Here, Student() is the constructor because its name is the same as the class name Student.
Constructor Syntax
public ClassName()
{
// Initialization code
}
}
| Rule | Explanation |
|---|---|
| Same name as class | Constructor name must match the class name. |
| No return type | A constructor does not have a return type. |
| Called automatically | It is called when an object is created. |
| Used for initialization | It can initialize fields and properties. |
Default Constructor
A constructor that does not take any parameters is called a parameterless constructor. It is commonly called a default constructor in beginner-level discussions.
public Student()
{
Console.WriteLine( "Default constructor called.");
}
}
Student student = new Student();
When new Student() is executed, the constructor runs automatically.
Constructor Provided by the Compiler
If a class does not declare any instance constructor, C# provides an implicit parameterless constructor. This allows an object to be created using the new keyword.
public string Name { get; set; }
}
Student student = new Student();
Here, no constructor is explicitly written. The compiler provides a parameterless constructor because the class does not declare an instance constructor.
Parameterized Constructor
A constructor that accepts one or more parameters is called a parameterized constructor. It allows us to initialize an object with values at the time of object creation.
public int Id { get; set; }
public string Name { get; set; }
public Student( int id, string name)
{
Id = id;
Name = name;
}
}
Student student = new Student( 101, "Rahul");
The values 101 and "Rahul" are passed to the constructor during object creation. The constructor assigns these values to the object's properties.
Using the this Keyword
The this keyword refers to the current object. It is commonly used when constructor parameters have the same names as class properties.
public int Id { get; set; }
public string Name { get; set; }
public Student( int Id, string Name)
{
this.Id = Id;
this.Name = Name;
}
}
Here, this.Id refers to the property of the current object, while Id refers to the constructor parameter. The same applies to this.Name and Name.
Constructor with Multiple Parameters
A constructor can accept multiple parameters when an object requires several values during initialization.
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public double Salary { get; set; }
public Employee( int id, string name, string department, double salary)
{
this.Id = id;
this.Name = name;
this.Department = department;
this.Salary = salary;
}
}
Employee employee = new Employee( 101, "Amit", "IT", 55000);
Constructor Overloading
A class can have multiple constructors with different parameter lists. This is called constructor overloading.
Constructors can be overloaded by changing the number, type, or combination of parameters.
// Parameterless constructor
public Student()
{
Name = "Unknown";
}
// One parameter
public Student( string name)
{
Name = name;
}
// Two parameters
public Student( int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
Now we can create Student objects in different ways depending on the information available at the time of creation.
Student s2 = new Student( "Rahul");
Student s3 = new Student( 101, "Priya");
Constructor Chaining
Constructor chaining allows one constructor to call another constructor in the same class. The this() syntax can be used for this purpose.
public int Id { get; set; }
public string Name { get; set; }
public Student() : this(0, "Unknown")
{
}
public Student( int id, string name)
{
Id = id;
Name = name;
}
}
Here, the parameterless constructor calls the constructor that accepts id and name. This helps avoid duplicate initialization code.
Constructor vs Object Initializer
C# also provides object initializer syntax. It can be useful when you want to create an object and assign properties directly.
Id = 101,
Name = "Rahul"
};
Object initializers are different from constructors. A constructor performs initialization logic, while an object initializer assigns accessible properties or fields after the object has been created.
Example: Employee 🤓🌍
In a real application, an Employee object may require important information such as employee ID, name, department, and salary when it is created.
public int Id { get; set; }
public string Name { get; set; }
string Department { get; set; }
public Employee( int id, string name, string department)
{
this.Id = id;
this.Name = name;
this.Department = department;
}
}
Employee employee = new Employee( 101, "Amit", "Development");
The constructor ensures that every Employee object is initialized with the required information when it is created.
Constructor vs Method
| Constructor | Method |
|---|---|
| Has the same name as the class. | Can have any valid method name. |
| Does not have a return type. | Has a return type or void. |
| Called automatically during object creation. | Usually called explicitly. |
| Mainly used for initialization. | Mainly used to perform an operation or behavior. |
Constructors and Inheritance
Constructors also play an important role when inheritance is used. When a derived class object is created, the base class constructor is involved in initializing the base part of the object.
public Person()
{
Console.WriteLine( "Person constructor");
}
}
class Student : Person {
public Student()
{
Console.WriteLine( "Student constructor");
}
}
Student student = new Student();
In inheritance, constructor execution follows the class hierarchy. The base class portion is initialized before the derived class constructor body completes its initialization.
Important Constructor Rules
- Constructor name must be the same as the class name.
- A constructor cannot have a return type.
- Constructors are called when objects are initialized.
- A class can have multiple overloaded constructors.
- Constructors can have parameters.
- Constructors can call other constructors using constructor chaining.
- A constructor cannot be inherited like a normal member.
Common Beginner Mistakes
- Giving a constructor a return type such as void.
- Giving the constructor a different name from the class.
- Forgetting that declaring a parameterized constructor means a parameterless constructor is not automatically supplied.
- Passing the wrong number or type of arguments while creating an object.
- Confusing constructors with normal methods.
- Putting too much business logic inside constructors.
Constructor Best Practices
- Use constructors to establish a valid initial state for an object.
- Keep constructor logic simple and focused on initialization.
- Use meaningful parameter names.
- Use this when it improves clarity between parameters and properties.
- Use constructor overloading when different initialization options are genuinely required.
- Avoid performing expensive or unrelated operations unnecessarily inside constructors.
CIIT Practical Point
In real-world C# applications, constructors are frequently used to initialize models, services, configuration objects, and other application components.
In ASP.NET Core applications, constructors are also commonly used for Dependency Injection, where required services are provided to a class through its constructor.
Therefore, understanding constructors is important before moving to advanced OOP concepts and ASP.NET Core development.
CIIT Interview Points
- What is a constructor in C#?
- Why are constructors used?
- What is a parameterless constructor?
- What is a parameterized constructor?
- What is constructor overloading?
- Can a constructor have a return type?
- What is the purpose of the this keyword?
- What happens if you declare a parameterized constructor but no parameterless constructor?
- What is constructor chaining?
- How are constructors used with Dependency Injection in ASP.NET Core?
Summary
- A constructor is used to initialize an object.
- A constructor has the same name as its class.
- A constructor does not have a return type.
- A constructor is called when an object is created.
- Constructors can be parameterless or parameterized.
- A class can contain multiple overloaded constructors.
- The this keyword can refer to the current object and can also participate in constructor chaining.
- Constructors are widely used in professional C# and ASP.NET Core applications.
Practice Questions
- Create a class named Student with a parameterless constructor.
- Create a parameterized constructor that accepts student ID and name.
- Create two objects using different constructors.
- Demonstrate constructor overloading.
- Use the this keyword inside a constructor.
- Create an Employee class and initialize its Id, Name, and Department using a constructor.
- Explain the difference between a constructor and a method.
- Explain constructor chaining with an example.