3

I would like to know if there is a method to write the below code in VB. ( Right now the equivalent VB.NET code looks too verbose )

List<DemoUsers> users = new List<DemoUsers>();
users.Add(new DemoUsers
{
    UserName = "name1",
    UserAddress = "Address1"
});

Right now I am writing it in VB.NET like

Dim users As New List(Of DemoUsers)

Dim usr1 As New DemoUsers()
usr1.UserName = "name1"
usr1.UserAddress = "Address1"

users.Add(usr1)

Does VB.NET have an equivalent C# short-hand? Also whats this short-hand method in C# called.

P.S: Could not google this short-hand notation availability as I dont know whats it called. Is there a name to call it?

naveen
  • 53,448
  • 46
  • 161
  • 251

6 Answers6

10

This is an object initializer, which also exists in VB:

New DemoUsers With { .UserName = "name1", .UserAddress = "Address1" }

Note that your C# could be even cleaner if you also use a collection initialzer:

var users = new List<DemoUsers>
{
    new DemoUsers { UserName = "name1", UserAddress = "Address1" }
};

And yes, collection initializers exist in VB too.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

You could take a look at the With keyword:

Dim usr1 As New DemoUsers()

With usr1
    .UserName = "name1"
    .UserAddress = "Address1"
End With

You can also use this in an object initializer:

Dim usr1 As New DemoUsers With { .UserName = "name1", 
                                 .UserAddress = "Address1" }
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
4
Dim users As New List(Of DemoUsers)()
users.Add(New DemoUsers() With { _
    Key .UserName = "name1", _
    Key .UserAddress = "Address1" _
})

I used http://www.developerfusion.com/tools/convert/csharp-to-vb/

Joe
  • 2,496
  • 1
  • 22
  • 30
1

This is using a feature called Object Initializer.

See this SO answer regarding object initializers in VB.Net.

Community
  • 1
  • 1
Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
0

It's called an object initializer:

Dim cust1 As New Customer With {.Name = "Toni Poe", 
                                .City = "Louisville"}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
CyberDude
  • 8,541
  • 5
  • 29
  • 47
0

Its called object initializer syntax.

In VB

Dim usr1 As New DemoUsers() With
{
    .UserName = "name1",
    .UserAddress = "Address1"
}
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30