Object Initializers
In VB 8.0, after instantiating an object, you would normally initialize the various properties of the object explicitly, like this:
Dim ptB = New Point
With ptB
.X = 5
.Y = 3
End With
But in VB 9.0, you can initialize an object at the same time it is instantiated. You accomplish this using object initializers. With them, the above statements can be rewritten like this:
Dim ptB = New Point With {.X = 5, .Y = 3}
The "." indicates the property that you are initializing. If the class has
constructor(s), you can also combine the constructor with the object initializer. For example, the
Size class contains two overloaded constructors, one of which takes in a
Point object. The following code shows you how to instantiate a
Size class using a constructor, as well as the object initializers:
Dim s As New Size(New Point(4, 5)) With {.Height = 30, .Width = 40}
You can also use the object initializers with arrays:
Dim pts() As Point = _
{New Point With {.X = 1, .Y = 2}, _
New Point With {.X = 3, .Y = 4}, _
New Point With {.X = 5, .Y = 6}}
Anonymous Types
Another new feature in VB 9.0 is the
anonymous type. Anonymous type allows you to define a new type without having to define a class. Consider the following example:
Dim contact1 = New With { _
.id = "54321", _
.Name = "Wei-Meng Lee", _
.email = "weimenglee@learn2develop.net" _
}
Here, the
Contact1 object has three properties
email, all of which are initialized during the instantiation stage. Moreover, you can change the values of these properties:
contact1.Name = "Lee, Wei-Meng"
contact1.email = "weimenglee@gmail.com"
However, there are times that you want to make certain properties read-only. To do so, use the
Key keyword. The following shows three more objects created using anonymous types, but this time their
id and
email properties are read-only:
Dim contact2 = New With { _
Key .ID = "12345", _
.Name = "Richard Wells", _
Key .email = "richard@company.net" _
}
Dim contact3 = New With { _
Key .ID = "12345", _
.Name = "Wells, Richard", _
Key .email = "richard@company.net" _
}
Dim contact4 = New With { _
Key .ID = "54321", _
.Name = "Wells, Richard", _
Key .email = "richard@company.net" _
}
To compare the equality of two anonymous types, use the
Equals() method. Two anonymous types are considered equal only if the values of their key properties (read-only) are the same, as the following example illustrates:
MsgBox(contact1.Equals(contact2)) '---returns False---
MsgBox(contact1.Equals(contact1)) '---returns True---
MsgBox(contact2.Equals(contact3)) '---returns True---
MsgBox(contact3.Equals(contact4)) '---returns False---