Câu hỏi phỏng vấn C#
Câu hỏi

What is the Constru...

Câu trả lời

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#:

csharp Copy
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:

  1. Reduces code duplication and improves readability by avoiding repeating the same initialization logic in multiple constructors[4].
  2. Enforces the inheritance hierarchy and the principle of least knowledge by ensuring the base class i...
senior

senior

Gợi ý câu hỏi phỏng vấn

expert

Could you explain the difference between Func vs. Action vs. Predicate ?

entry

What is an Object ?

middle

What is the difference between ref and out keywords?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào