Wednesday, November 28, 2007

VB 9 Series - Object Initializers

Welcome to the second article of VB 9 Series. In this article I'll try to explain the new functionality introduced in Visual Basic 9 i.e. Object Initialization... with the help of this technology you can very well separate object Initialization logic, you may had some problem or have to write long code to initialize certain values in your object and can't find those in the constructor consider the following example code:

Public Class
Customer

.........Private _name As String
.........Private _address As String
.........Private _City As String

.........Public Sub New()
..................'default constructor
.........End Sub

.........Public Sub New(ByVal Name As String)
.................._name = Name
.........End Sub

.........Public Property CustomerName() As String
.........Get
..................Return _name
.........End Get
.........Set(ByVal value As String)
.................._name = value
.........End Set
.........End Property

......... Public Property Address() As String
.........Get
..................Return _address
.........End Get
.........Set(ByVal value As String)
.................._address = value
.........End Set
.........End Property

.........Public Property City() As String
.........Get
..................Return _City
.........End Get
.........Set(ByVal value As String)
.................._City = value
.........End Set
.........End Property

End Class

And then you Instantiate the object of this class like this:

.........Dim MyCustomer As New Customer("Ali")
.........MyCustomer.Address = "xxx"
.........MyCustomer.City = "Lahore"

Or can also use the bellow code to initialize the values:

.........Dim MyCustomer As New Customer("Ali")
.........With MyCustomer
...................Address = "xxx"
...................City = "Lahore"
.........End With

But to keep the initialization logic togather VB 9 has introduce new functionality now you can use the bellow code to set the values while instantiating an object:

.........Dim myCustomer As New Customer("Ali") With {.Address = "xxx", .City = "Lahore"}

IntelliSense will help you to set the different properties related with the object.

I hope you get the idea of this yet new powerful feature of VB 9.

Good Luck !

No comments: