What is Constructor overloading? with code

Constructor Overloading is a technique to define multiple constructors within a class with different sets of parameters.  

The first constructor with no parameters serves as the default constructor. It initializes the value field to 0.

The second constructor with the int parameter allows you to provide a specific value for the value field during object creation.

Constructor overloading in C# refers to the ability to define multiple constructors with different parameter lists within a class. Each overloaded constructor provides a different way to create objects of the class by accepting different combinations of input parameters.

Constructor overloading allows you to create objects with different initial states or to provide flexibility in object creation based on varying input requirements.

Here's an example that demonstrates constructor overloading:

public class MyClass { private int value; public MyClass() { value = 0; // Default initialization } public MyClass(int value) { this.value = value; // Custom initialization } }

In this example, the MyClass class has two constructors: one with no parameters and another with an int parameter.

By providing different constructors, you can create instances of MyClass using different constructor invocations:

MyClass obj1 = new MyClass(); // Uses the default constructor MyClass obj2 = new MyClass(42); // Uses the constructor with int parameter

In the above example, obj1 is created using the default constructor, which initializes the value field to 0. obj2 is created using the constructor with the int parameter, allowing you to provide a custom value of 42 for the value field during object creation.

Constructor overloading allows you to create objects with different initial states or to cater to different scenarios where varying input parameters are required for object initialization.


 

Post a Comment

Previous Post Next Post