Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dim X as New Y vs. Dim X as Y = New Y()

Duplicate

Whats the difference between declaring as new and as something new something i

Sad that I don't know this, but can anyone explain the difference between:

Dim X as New Y

and

Dim X as Y = New Y()
like image 804
madcolor Avatar asked May 11 '09 14:05

madcolor


2 Answers

The first just infers that the type is Y. The second specifies it. This allows you to write things like:

Dim X as IList(Of String) = New List(Of String)

That then limits the scope of the choice to use List(Of String) - which means that later on you might choose to use a different implementation of IList(Of String), and it'll still compile.

Of course, the shorter version does have the benefit of brevity - which can be important if you have very long type names (e.g. using nested generics). It's also required for anonymous types, where you can't express the type of X.

like image 176
Jon Skeet Avatar answered Sep 30 '22 18:09

Jon Skeet


Jon Skeet has already provided the correct answer, but I thought I'd add a little extra...

Although it was not specifically your question, there is an important difference between

Dim X = New Y()

and

Dim X As Y = New Y()

The differences here actually depend on the version of VB.NET you are using.


VB.NET 7 & 8

Dim X = New Y()

This defines X as a variable of type object (System.Object), then creates an object of type Y and assigns it to X. Note that this only works when you've defined Option Strict Off, otherwise it won't even compile. It's really just a carry-over from the syntax of the days of VB6 and earlier, and is generally discouraged.

Dim X as Y = New Y()

This does exactly the same, except that X is now strongly-typed, in other words it is of type Y rather than object (from which all types inherit, including value types when they are boxed).

VB.NET 9 and subsequently

Dim X = New Y()

The difference here (for the newer version of VB.NET) is that type inference is taking effect here. Because you don't specify any type, but it is obvious to the compiler that New Y() returns an instance of type Y, it automatically infers that the type of X should be Y, which is a lot more specific than object. Type interference also works on more complex expressions.

Dim X as Y = New Y()

This is interepreted in precisely the same was as in VB.NET 7 & 8.


To conclude, you can effectively replace

Dim X As New Y()

with

Dim X = New Y()

in VB.NET 9 and the compiler will interpret the two lines exactly the same because of type inference. In earlier versions, however, the second line will be weakly typed (of type object), which is not advisable. Again, not a direct answer to the question, but I thought this might be helpful to point out.

like image 44
Noldorin Avatar answered Sep 30 '22 17:09

Noldorin