Saturday, September 13, 2008

C# : Initializers and Constructors

When ctor is executed, it is executed as follows :
ctor
{
initializers;
base();
code of current ctor();
}
Hence, when you have a long hierarchy of classes, you see that initializers run from D -> B and constructors run from B -> D.
Okay, now thats a fact, but why does this happen? --> Derived ctor may rely on state initialized by base ctor... how? --> base may contain a variable which is initialized in base ctor, and dervied ctor might be using that variable.

You should avoid virtual method calls in a ctor of a non sealed type why? --> If a base type ctor causes a virtual method call to be invoked, the most derived type's method will be dispatched even though the derived type's ctor has not completed execution. And so there might be null ref exceptions or unpredictable results.

No comments: