What is the Constructor Chaining in C#?
What is the Constructor Chaining in C#?
Constructor chaining in C# allows one constructor to call another constructor of the same class or a base class to share initialization code. It is implemented using the : this() keyword to call another constructor in the same class, or : base() to call a constructor in the base class.
Here's an example of constructor chaining in C#:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// default constructor
public Person()
: this("Unknown", 0)
{
}
// constructor with two parameters
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
In this example, the default constructor calls the constructor with two parameters using : this("Unknown", 0). This allows the default constructor to reuse the initialization logic without duplicating code.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.