C# Constructor

In C#, a constructor is similar to a method that is invoked when an object of the class is created.

However, unlike methods, a constructor:

  • has the same name as that of the class

  • does not have any return type

Create a C# constructor

Here's how we create a constructor in C#

class Car {
  
  // constructor
  Car() {
    //code
  }

}

Here, Car() is a constructor. It has the same name as its class.

Call a Constructor

Once we create a constructor, we can call it using the new keyword. For example,

In C#, a constructor is called when we try to create an object of a class. For example,

Here, we are calling the Car() constructor to create an object car1.

Types of Constructors

There are the following types of constructors:

  • Parameterless Constructor

  • Parameterized Constructor

  • Default Constructor

1.Parameterless Constructor

When we create a constructor without parameters, it is known as a parameterless constructor. For example,

2.Parameterized Constructor

In C#, a constructor can also accept parameters. It is called a parameterized constructor. For example,

In the above example, we have created a constructor named Car(). The constructor takes two parameters: theBrand and thePrice.

3.Default Constructor

If we have not defined a constructor in our class, then the C# will automatically create a default constructor with an empty code and no parameters. For example,

In the above example, we have not created any constructor in the Carclass. However, while creating an object, we are calling the constructor.

Car c = new Car();

Here, C# automatically creates a default constructor. The default constructor initializes any uninitialized variable with the default value.

Note: In the default constructor, all the numeric fields are initialized to 0, whereas string and object are initialized as null.

C# Constructor Overloading

In C#, we can create two or more constructor in a class. It is known as constructor overloading. For example,

In the above example, we have overloaded the Car constructor:

  • one constructor has one parameter

  • another has two parameter

    Based on the number of the argument passed during the constructor call, the corresponding constructor is called.

Here,

  • Object car1 - calls constructor with one parameter

  • Object car2 - calls constructor with two parameters

Last updated