views:

48

answers:

4

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 infer 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.

+4  A: 

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
Hans Passant
Thank you for your answer. Is one way considered more "proper" than another way, or is it really up to the programmer?
dcp
@dcp - the "proper" way most of the time is a third option you didn't use: `Dim x As New Exception("this is an exception")`
Joel Coehoorn
@dcp: type inference is quite nice with few drawbacks, although your colleagues might find it less readable right now. Don't hesitate to use it. Beware that you cannot use it everywhere, only on local variables.
Hans Passant
@Hans: What drawbacks?
Konrad Rudolph
@Konrad: "cannot use everywhere".
Hans Passant
@Joel: ah! double quote. Nobody liked REM. Thanks for the tip :)
Hans Passant
+2  A: 

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.

STW
+2  A: 

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 :)

ho1
true; this isn't affected by `Option Infer` -- but also can only be used when `New` ing up a variable
STW
A: 

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.

Greg Treleaven