Partilhar via


VB.NET 9.0: Object and Array Initializers

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!!!

Comments

  • Anonymous
    February 05, 2008
    Last week I was exploring VB.NET for the ISV demo delivery. Some findings I want to share with you. First

  • Anonymous
    June 22, 2009
    can we edit name value of objCusts(0)

  • Anonymous
    September 14, 2010
    Is it possible to initialize Lists which are members of the class using this method?

  • Anonymous
    September 27, 2010
    @LVS, yes you can initialize a List of custom class

  • Anonymous
    December 23, 2010
    c#


new List<String>() {"Value1", "Value2", "Value3"} Vb

New List(Of String) From {    "Value1", "Value2", "Value3" }

  • Anonymous
    July 31, 2013
    THANKS

  • Anonymous
    April 24, 2014
    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 ?