Saturday, August 25, 2007 12:00 AM
bart
Visual Basic 9.0 Feature Focus - Object Initializers
Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Object Initializers, a feature also available in C# 3.0 (see here). The problem this feature aims to fix is the following: how many times did you need to use some type and did you find youself looking at the constructor overload list to come to the conclusion the overload you'd like to have is missing (or maybe there's just a default parameterless constructor). So, in lots of cases you need additional properties to be set after calling a somewhat appropriate constructor. Let's give an example below:
Class Customer
Private _name As String
Private _age As Integer
Public Sub New(ByVal name As String)
_name = name
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Age() As Integer
Get
Return _age
End Get
Set(ByVal value As Integer)
_age = value
End Set
End Property
End Class
In order to construct an object of the type, you'll typically do something like this:
Dim c As New Customer("Bart")
c.Age = 24
or, especially if you have to set multiple properties,
Dim c As New Customer("Bart")
With c
.Age = 24
End With
I think everyone agrees initialization logic should be kept together, but the need for multiple initialization statements can complicate matters (what if someone inserts something between line one and two?). So a more convenient initialization syntax was added to Visual Basic 9.0 (and C# 3.0) to help with this:
Dim c As New Customer("Bart") With {.Age = 24}
With the aid of IntelliSense you get the following:
The With portion of the object initializer takes a comma separated list of initialization statements that can be used for all accessible fields and properties. You can split the initialization statement over multiple lines of code using the line continuation _. It seems Visual Basic got curly braces at last :-).
Happy coding!
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks
Filed under: VB 9.0