Tag: Initializer

  • New object initializer

    Visual Basic 9 has a new object initializer. This is the point: Any variable that the code creating the instance can reach, can be initialized using the initializer. This is an example class. It has two public data members (X and Y). Since they are public, they can be initialized using the new object initializer. The ToString function gives information on what data members are initialized.

    Public Class SomeClass
    Public X As String
    Public Y As String

    Public Overrides Function ToString() As String
    Dim Ret As New System.Text.StringBuilder()
    If Me.X Is Nothing Then
    Ret.AppendLine(“X = Nothing”)
    Else
    Ret.AppendLine(“X is initialized”)
    End If
    If Me.Y Is Nothing Then
    Ret.AppendLine(“Y = Nothing”)
    Else
    Ret.AppendLine(“Y is initialized”)
    End If
    Return Ret.ToString()
    End Function
    End Class

    This code compiles in both VB8 and VB9:

    Dim Obj As New SomeClass()
    Obj.X = “Hello”
    Debug.WriteLine(Obj.ToString())

    The output tells me that X is initialized, and that Y is not. In VB9, I can initialize any of the public members on the same line of code that creates the object. Here, Y is initialized:

    Dim Obj As New SomeClass With {.Y = “Yes”}
    Debug.WriteLine(Obj.ToString())

    And here, both X and Y is:

    Dim Obj As New SomeClass With {.X = “I am X”, .Y = “Yes”}
    Debug.WriteLine(Obj.ToString())

    This can also be used on public properties, and I guess that no-one writes classes that has public variables in production code.

    The reason this actually is cool, is that it doesn’t replace your constructors. Using the new object initializer does not bypass the call to the constructor. If, for example, the class doesn’t have a default constructor, but a constructor that takes one argument, the code that creates the instance would look like this:

    Dim Obj As New SomeClass(“Hello”) With {.X = “I am X”, .Y = “Yes”}