tags:

views:

271

answers:

3

I was just wondering if there is any difference between the two different new object initializers or is it just syntactic sugar.

So is:

Dim _StreamReader as New Streamreader(mystream)

and different to:

Dim _StreamReader as Streamreader = new streamreader(mystream)

Is there any difference under the hood? or are they both the same? Which one do you prefer to use?

+1  A: 

I'm not a VB guy, but as far as I can tell they're equivalent. According to MSDN's description of the Dim statement:

If you do not specify datatype, the variable takes the data type of initializer. If neither datatype nor initializer is present, by default, the data type is Object Data Type. If you specify both datatype and initializer, the data type of initializer must be convertible to datatype.

I won't pass comment on preference, as I don't use VB (except when answering statements).

Jon Skeet
+12  A: 

In VB.NET, they're identical. The As New variant is canonical.

In VB6, their semantics actually differed (apart form the obvious fact that VB6 didn't allow assignments in declarations): the As New variant would create an object that could never be Nothing. Rather, the runtime would ensure that the object was always properly initialized before each access to it.

Konrad Rudolph
+2  A: 

These statements are identical. Personally I prefer the "Dim x as New" syntax because it's more concise. There is no reason for writing the same type name in the same statement when it doesn't make a programatic difference. All it does is make you spend more time on the keyboard :)

JaredPar