Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET fill out object fields on creation

Tags:

vb.net

In C# when creating an object we can also (at the same time) fill out its properties. Is this possible in VB.NET?

For example:

MyObject obj = new MyObject
{
   Name = "Bill",
   Age = 50
};
like image 359
user441521 Avatar asked Mar 22 '13 14:03

user441521


1 Answers

Yes, it's possible:

Dim obj As New MyObject With { .Name = "Bill", .Age = 50 }

Two important things:

  1. Use With keyword after class name and before { ... }
  2. Property names have to be prefixed with a dot, so you have to use .Name instead of Name

For collection initializers use From keyword:

Dim obj as New List(Of String) From { "String1", "String2" }
like image 177
MarcinJuraszek Avatar answered Oct 18 '22 14:10

MarcinJuraszek