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

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

What is jagged array in C# and when to prefer jagged arrays over multi-dimensional arrays?

senior

What is the difference between Func<string,string> and delegate ?

senior

What happens when we Box or Unbox Nullable types?

Bình luận

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

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