How to create an object and set its properties in one line in VB.NET

Code

Code (Photo credit: three_sixteen)

This just took me forever to find, so to help out anyone else who needs to be able to do this:

In VB.NET if you want to create an object and set its properties on one line (and there isn’t a constructor that does what you want), the feature you’re looking for is called Object Initializers and the syntax is:

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

There’s also a similar thing called a Collection Initializer which lets you create an populate a collection on one line.  This is already possible with arrays using array literal syntax, but Collection Initializers let you do it with any collection type:

Dim names As New List(Of String) From {"Bob", "Susan"}
Enhanced by Zemanta