VB.NET 9.0: Object and Array Initializers

VB.NET 9.0: Object and Array Initializers

  • Comments 6

Last week I was exploring VB.NET for the ISV demo delivery. Some findings I want to share with you. First the object and Array Initializers

 

Let’s suppose we have a class called Customer

 

Public Class Customer

    Public Id As Integer

    Public Name As String

End Class

 

Now when you initialize this object in conventional VB.NET, this could be your approach,

 

Dim cust As New Customer()

 

With cust

    .Id = 1

    .Name = "VB.NET"

End With

 

Now in VB.NET 9.0 we do things in little differently,

 

Dim cust = New Customer() With {.Id = 2, .Name = "VB.NET 9.0"}

 

Also for array initialization in VB.NET we go for,

 

Dim objCusts(1) As Customer

objCusts(0) = New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}

objCusts(1) = New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}

 

In VB.NET 9.0 we write,

 

Dim objCusts() As Customer = { _

    New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}, _

    New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}}

 

It is small (to me simple), it is sweet.

 

Namoskar!!!

Leave a Comment
  • Please add 3 and 4 and type the answer here:
  • Post
  • Last week I was exploring VB.NET for the ISV demo delivery. Some findings I want to share with you. First

  • can we edit name value of objCusts(0)

  • Is it possible to initialize Lists which are members of the class using this method?

  • @LVS, yes you can initialize a List of custom class

  • THANKS

  • the more things you add to the langage the more ugly it's become.

    Its not small and it is more complexe. Now you have 2 new statements and a double  arrays in array that you use in a constructor with the "With" key word.

    And if we have an array of 1000 customers ?

Page 1 of 1 (6 items)