A base class has a constructor that initializes a critical resource. How do you guarantee the derived class correctly initializes this resource before its own initialization begins?

.NET interview question for Advanced practice.

Answer

Call the base class constructor explicitly using the base() keyword in the derived class constructor's initializer.

Explanation

The correct answer is B. C has a built-in, deterministic mechanism for this. By using the : base(...) syntax in the derived class's constructor, you explicitly invoke the desired base class constructor. The runtime guarantees that the base constructor will execute to completion before the first line of the derived class's constructor is executed. This ensures the base part of the object is fully initialized first. Option A is incorrect; the order is well-defined. Option C is a workaround that breaks the standard object construction pattern. Option D is overly complex, inefficient, and unnecessary.

Related Questions