Constructors in C#

As we know a constructor is a special type of method in a class that is called every time an instance of the class is created. It is generally used for initialization. The constructor has the same name as the class and it returns no value.

Consider Example 1

Example 1:

Implementing OOP in C# Example 1

In Example 1, we have a function of the same name as the class. This is the constructor for the class. In the constructor we assign a default value for the duration property. If the developer does not set any value for the duration property using the setDuration() even then the duration property of the semester object will have the value of 144, the default value that we have specified in the constructor.

1.   Parameterized Constructors

We can also have parameterized constructors just as we have in C++. We just pass either different number of arguments or the same number of arguments but of different types to make the runtime differentiate among them. For example, in Example 2 we have defined a parameterized constructor for the class semester so that the developer can set the value of the duration property in the constructor itself, instead of using the default value of 144.

Example 2:

Implementing OOP in C# Example 2

Now notice that two constructors exist. The one without parameters is the default constructor. The default constructor is called when no parameters are specified during object creation. The other constructor is called when parameters are passed during object creation. Consider the following snippet of code.

Example 3:

Implementing OOP in C# Example 3

The output of Example 3 would be,

Java Duration = 144
cSharp Duration = 180

The Java object invoked the default constructor as no parameters were passed to it, while the cSharp object invoked the parameterized constructor as an int value was passed to it.

Leave a comment