user7685699 user7685699 -4 years ago 93
Vb.net Question

Why do these similar variable declarations have different types?

Dim X as New Y vs. Dim X as Y = New Y() New Question:
Followup question to this thread:
Dim X as New Y vs. Dim X as Y = New Y()

I'm running VS2015 (VB 14) Can someone help me out here ? Given this class:

Public Class Form1
Dim test3 As New Example
Dim test4 = New Example
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim test1 As New Example
Dim test2 = New Example
test1.Mylist.Add("1")
test2.Mylist.Add("2")
End Sub
End Class
Class Example
Public Sub New()
Mylist = New List(Of String)
End Sub
Public Mylist As List(Of String)
End Class


Test4 is of type object NOT example as expected.

Thanks, -TD

Answer Source

Your confusion is understandable and is a consequence of the syntactic sugar that the language supports. You are taking advantage of Local Type Inference (Visual Basic) in the first example. This bit of sugar is only applicable at the procedure level and is the reason both test1 and test2 are of type Example.

In your second example of:

Dim test1 As New Example
Dim test2 = New Example
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  test1.Mylist.Add("1")
  test2.Mylist.Add("2")           
End Sub

The variable test2 is declared at the class level and as such is not eligible for type inference. Hence as declared, it will be of type Object. The code would be converted to something similar to the following.

Dim test1 As Example
Dim test2 As Object
Public Sub New()
   test1 = New Example()
   test2 = New Example()
   InitializeComponent()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  test1.Mylist.Add("1")
  test2.Mylist.Add("2")           
End Sub

Edit: The original post has been edited while I was typing out this answer, but the reasoning remains the same. As such I will not modify this to reflect the changes to the original post code example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download