简体   繁体   中英

Why does this code compile in VS2005 but not VS2008 (VB.NET)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM