Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2008-12-13
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”}
Categories: Visual Basic 9
Tags: Initializer
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply