C# and VB.NET: Field initialization differences

December 9, 2014 - .NET, C#, Programming, Visual Basic

I found this to be an interesting discovery. I always somewhat expected each .NET language to work in a similar way with regards to things such as field initialization, but as it turns out, C# and VB.NET work differently in this regard, and in both cases it is due to design decisions with the language themselves. To best show this, I created two equivalent class heirarchies in C# and VB.NET



Both are effective a base class with a non-default constructor which has a static field and a instance field, and a class derived from that class which implements a similar non-default constructor and sets a derived instance which along with a static field are both initialized at their declaration, then creates an instance of the derived type.

I breakpointed all statements in the program, and traced through each one. in C# the progress was:

  1. Derived Static field initialized
  2. Derived Instance field initialized
  3. Base Static Field Initialized
  4. Base Instance Field Initialized
  5. Base Constructor execution
  6. Derived Constructor Execution

In VB.NET, we have the following order:

  1. Derived Static Field Initialized
  2. Base Static Field Initialized
  3. Base Instance Field Initialized
  4. Base Constructor Execution
  5. Derived Instance Field Initialized
  6. Derived Constructor execution

This has interesting repercussions. for VB.NET the main repercussion is that if you call a virtual (Overridable) method from the base constructor, within that virtual method the instance fields will not be initialized, whereas, with C#, they will be. On the C# side, it is likely the reason that derived instance fields cannot be initialized by calling an instance method, because the initialization of instance fields occurs before the base class static and instance fields have been initialized, so the class state within that method would be difficult to predict. Arguably, it seems that Visual Basic .NET takes a more “You probably know what you are doing” approach, whereas C# is more careful and “safety” conscious.

Have something to say about this post? Comment!

Tags: , ,