What is the Constru...
What is the Constru...
Constructor chaining in C# allows one constructor to call another constructor of the same class or a base class to share initialization code[1][2][3][4]. 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[1][2][4].
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[1][2][4].
The main benefits of constructor chaining are:
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào