C# Constructor

In C#, a constructor is a special method that is used to initialize an object of a class. The constructor is called when an instance of a class is created using the new keyword.

A constructor has the same name as the class and no return type, not even void.

Default Constructor

If a class does not have any constructor, C# provides a default constructor. The default constructor takes no parameters and does nothing.

1public class ExampleClass 2{ 3 public ExampleClass() 4 { 5 // Default Constructor 6 } 7}

Parameterized Constructor

A constructor with parameters is called a parameterized constructor. The parameterized constructor is used to set the initial values of the class properties at the time of object creation.

1public class ExampleClass 2{ 3 private string name; 4 private int age; 5 6 public ExampleClass(string name, int age) 7 { 8 this.name = name; 9 this.age = age; 10 } 11}

Constructor Overloading

In C#, it is possible to have multiple constructors with different parameters. This is called constructor overloading.

1public class ExampleClass 2{ 3 private string name; 4 private int age; 5 6 public ExampleClass() 7 { 8 this.name = ""; 9 this.age = 0; 10 } 11 12 public ExampleClass(string name, int age) 13 { 14 this.name = name; 15 this.age = age; 16 } 17}

Access Modifiers

The access modifiers such as public, private, protected can be used with constructors to control their access.

1public class ExampleClass 2{ 3 private string name; 4 private int age; 5 6 public ExampleClass() 7 { 8 this.name = ""; 9 this.age = 0; 10 } 11 12 public ExampleClass(string name, int age) 13 { 14 this.name = name; 15 this.age = age; 16 } 17 18 private ExampleClass(string name) 19 { 20 this.name = name; 21 this.age = 0; 22 } 23}

The above code defines two public constructors and a private constructor.