New {object} vs {object} = new {object}

I'm just wondering if there is a difference between two different initializers of new objects or is it just syntactic sugar.

So:

Dim _StreamReader as New Streamreader(mystream) 

and differs from:

 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?

+6
source share
3 answers

In VB.NET they are identical. The As New variation is canonical.

In VB6, their semantics were actually different (as opposed to the obvious fact that VB6 did not allow assignments in declarations): the As New option would create an object that could never be Nothing . Rather, the runtime ensures that the object has always been correctly initialized before each access to it.

+14
source share

These statements are identical. Personally, I prefer the syntax "Dim x as New" because it is more concise. There is no reason to write the same type name in the same statement if it does not make programmatic difference. All he does is make more time on the keyboard :)

+2
source share

I'm not a VB guy, but as far as I can tell, they are equivalent. According to the MSDN Dim instructions :

If you do not specify a data type, the variable accepts a data type initializer. If neither the data type nor the Initializer is present, by default, the data type is the data type of the object. If you specify both a data type and an initializer, the data type initializer must be converted to a Data Type.

I will not pass a comment about preference, since I do not use VB (except when I answer).

+1
source share

All Articles