Constructor chaining in C# refers to the process of calling one constructor from another constructor within the same class or from a derived class to the base class. This allows for more efficient and organized initialization of objects.
In C#, a class can have multiple constructors, each with a different set of parameters or overloads. When you create an instance of a class using the new keyword, one of the constructors is invoked to initialize the object.
Constructor chaining is useful when you have multiple constructors in a class and you want to reuse initialization logic present in one constructor from another constructor. This helps avoid duplicating code and promotes code reusability.
Within a class
Here's an example of constructor chaining in C#:
public class MyClass
{
private int value;
// Constructor with no parameters (default constructor)
public MyClass() : this(0) { }
// Constructor with a parameter
public MyClass(int value)
{
this.value = value;
}
}
In this example, the constructor public MyClass(int value) is chaining to the constructor public MyClass(). When you create an instance of MyClass using the default constructor new MyClass(), it will call the parameterized constructor with the default value of 0.
Between classes
Constructor chaining can also involve chaining to constructors in the base class, especially in the case of inheritance where a derived class needs to initialize the base class before performing its own initialization.
public class BaseClass
{
private int baseValue;
public BaseClass(int value)
{
baseValue = value;
}
}
public class DerivedClass : BaseClass
{
private int derivedValue;
public DerivedClass(int baseValue, int derivedValue) : base(baseValue)
{
this.derivedValue = derivedValue;
}
}
In this example, the constructor in the DerivedClass is chaining to the constructor of the BaseClass using base(baseValue) to initialize the base class before performing additional initialization for the derived class.
No comments:
Post a Comment