What is object initializer and how to write it in VB.NET?

0 votes
asked Jun 13, 2013 in VB.NET by anonymous

Pls post me some sample code for object intializer.

Share

1 Answer

+1 vote
answered Jun 14, 2013 by Aadhira (1,213 points)
selected Jun 18, 2013 by administrator
 
Best answer

Object Initializer is new way of initializing the object, starting from .net framework 3.0
This is used to initialize the object properties during the time of instance creation itself. To make it clear, consider that you have class called Customer as below.

Public Class Customer
         private _firstName as String
         Public Property FirstName() As String
            Get
                Return _firstName
            End Get
            Set(ByVal value As String)
                 _firstName = value
            End Set
         End Property

         private _lastName as String
         Public Property LastName() As String
            Get
                Return _lastName
            End Get
            Set(ByVal value As String)
                 _lastName = value
            End Set
         End Property
End Class

When you want to create an object for class Customer and set values of the property, before dot net 3.0, you might have done like below.

Dim _customer As New Customer();
_customer.FirstName = "Frank"
_customer.LastName = "Anderson"

But with .net 3.0 and after, we can create the same as below code.

Dim _customer As New Customer() With { .FirstName = "Frank", .LastName = "Anderson" }

Both are going to give the same result.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...