VB.net Instance Variable Initializers vs the Constructor

Filed under VB Feng Shui

I ran into a very peculiar problem several days ago. Essentially, I had a class, with a few properties. One of those properties had some initialization code for a backing variable, like so:

   Public Property Count() As Integer
         Return _count
      End Get
      Set(ByVal Value As Integer)
         _count = Value
      End Set
   End Property
   Private _count As Integer = _collection.Count

Now, granted, this is a little contrived. But the idea is that this particular property is initialized with a value from a private object (the _collection variable), that is set up during the constructor.

The problem was that the app was throwing an object not initialized when try to initially set the _count variable’s value.

This completely threw me. How on earth was my constructor not being called? After some debugging, I quickly discovered that the constructor is called after all these private variable initialization lines are executed! Now, that doesn’t really make a whole lot of sense, but, it’s what’s happening.

Only later did I come across this post by Patrick Steele. He’s got a great explanation and description of what’s happening there, so I won’t repeat that.

But the key to the whole issue is a quote by him from the Visual Basic Language Specification:

When a constructor’s first statement is of the form MyBase.New(…), the constructor implicitly performs the initializations specified by the variable initializers of the instance variables declared in the type. This corresponds to a sequence of assignments that are executed immediately after invoking the direct base type constructor. Such ordering ensures that all base instance variables are initialized by their variable initializers before any statements that have access to the instance are executed.

(The emphasis is Patrick’s)

He goes on to quote the relevant part of the C# spec, which explicitly states exactly the opposite behavior for it’s initializers and constructors!

I haven’t been able to find any quote as to why there’s a difference in behavior, or more specifically, why on earth VB’s behavior in this case seems so wrong.

If anyone knows, please comment!

Post a Comment

Your email is never published nor shared. Required fields are marked *