Option Infer in VB by ThinqLinq

Option Infer in VB

With the upcoming language enhancements in VB and C#, some leads are concerned with code maintainability when not explicitly declaring the resulting type on an anonymous type. If you are not familiar with local variable type inference, here are a couple examples:

VB:

dim i = 5

dim j = "foo"

C#:

var i = 5;

var j = "foo";

In both cases, the first variable (i) is inferred as an integer and the second is inferred as a string. In some cases, particularly in a RAD environment, we want to view object results without needing to declare a specific type for each desired result set.

In some cases, relying on inferred types makes code maintainability more difficult. Although the type may be easily understandable when the code is first written, groking it when you have to revisit the code in a year could cause more time than it would have taken to explicitly declare it in the first place. To assist with this, a new Option declaration has been added to help "force" the developers to declare the type if you prefer. In this case, you would probably want to make the following declaration:

Option Strict On
Option Explicit On
Option Infer Off

With this, you will be forced to declare your type. By default Option Infer will be On for new projects and Off for existing projects.

One word of warning. If you specify Option Infer off and Option Strict Off, your objects will be automatically inferred as Object. For instances of type Object, rather than using extension methods, VB will try to call the method via reflection. In that case, if you try to apply an extension method (like "Take"), you can likely get a runtime exception rather than compile time check. This is easily fixable by requiring Option Strict On along with Option Infer Off which will force you to declare your type (other than object) and allow the compiler to match up the proper extension method.

I realize there are plenty of cases where Option Infer needs to be turned on, particularly in the case of using Anonymous types, but at least we have the ability to turn it on only when it is essential.

Posted on - Comment
Categories: VB -
comments powered by Disqus