开发者

VB.Net variable declaration

I notice that both of these compile without any compiler warnings or errors, even with Option Strict and Option Explicit both turned on:

    Dim x As Exception = New Exception("this is a test")
    Dim y = New Exception("this is another test")

My question is, is it more proper to use the first way (see variable x) or the second way (see variable y)? My guess is that VB doesn't need the As clause since the variable is being initialized in place, so the compiler can i开发者_高级运维nfer the type.

I tend to like the first way as it just "feels" right and is more consistent with other languages like C#, just wondered if there was some good reason for one way over the other. I guess it's really personal choice.


Behold the wonder of Option Infer On, the compiler figures out the type of "y" automatically. Available since VS2008. You'll get the error you are looking for by turning it off:

Option Strict On
Option Infer Off

Module Module1
    Sub Main()
        Dim x As Exception = New Exception("this is a test")
        Dim y = New Exception("this is another test")   ''# error BC30209
        Dim z As New Exception("this is a third test")
    End Sub
End Module


I'd do Dim x As New Exception("this is a test"). Best of both worlds, no infering but you still only have to type Exception once :)


Option Infer is what controls this compiler feature. Both are equivalent--this is similar to the (moot) C# debate about whether to use the var keyword. My two-cents is to leave it up to the individual developer, however many people will likely say to establish a convention and follow it.


I think the first one (with the variable type declaration) would be the safest to use. If the program is small, it won't really make a difference, but for larger program's, there could be a noticeable compiler lag. So (in my opinion) declaring the type is the best thing to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜