views:

89

answers:

1

I'm in the process of migrating a VB.NET web application from Visual Studio 2005 (.NET 2.0) to Visual Studio 2008 (.NET 3.5) and while it was mostly straightforward I encountered a problem which took some time to resolve.

The code in question reads:

Dim serviceArray = New SecurityLayer.Model.Service()
serviceArray = new SecurityLayer.SecurityBusinessController.GetServices(userId)

Which compiles in VS2005/.NET2.0 but fails in VS2008/.NET3.5 with the following error:

Value of type '1-dimensional array of SecurityLayer.Model.Service' cannot be converted to 'SecurityLayer.Model.Service'

This indicates that serviceArray is not declared as an array and Reading the MSDN documentation it does not look like the syntax has changed between the versions but it states that curly braces are required whether any values are being passed in or not. Sure enough, adding curly braces to it's declaration resolves the problem (and the compiler moves onto the next instance!).

Dim serviceArray = New SecurityLayer.Model.Service(){}
serviceArray = new SecurityLayer.SecurityBusinessController.GetServices(userId)

After updating all of the instances of this declaration the code now builds and runs as expected.

Option Explicit and Option Strict are the same in both IDEs so it can't be that (or at least that's what I'm assuming).

So my question is, why did this build in VS2005/.NET2.0 and not in VS2008/.NET3.5?

Thanks in advance

+6  A: 

VB.NET version 9 acquired type inference. Previously your Dim declaration was untyped, serviceArray was of type Object. Now, the compiler inferred from your previous usage that serviceArray is of type Service. Using the same variable to store different objects is fishy.

Hans Passant
Ah - spot on! I normally work with C# so not really up to speed on the VB.NET side of things. As a test I've removed the braces in VS2008 (to generate the error) and then added 'Option Infer Off' to the top of the class. The error duly disappeared!Needless to say I've not left it like this, reverting to the correct syntax instead. Good to know the cause though - thanks.
DilbertDave
As long as you're tinkering with Option, be sure to add Option Explicit On. It catches *many* mistakes like this.
Hans Passant
Options Explicit seems to be on by Default in the IDE (always worth checking though)
DilbertDave
Option Explicit should **always** be on. However to catch this specific problem, try turning on the compiler check for "implicit type; object assumed". Project properties, compile tab.
MarkJ