In C# you can create an instance like this:
Custom mycustomelement = new Custom { ElenentName = "My Custom Element" };
I wonder how I can create instance like this in Visual Basic and what this type of creating instance is called.
It's called an object initializer, and the corresponding VB.NET syntax is:
Dim mycustomelement As New Custom With { .ElementName = "My Custom Element" }
(Note the dot (.
) before the property name, which matches the syntax of VB's With
statement.)
Note that there is a subtle difference between C# and VB when using the object initializer syntax for anonymous types: In C#, all properties are immutable; in VB, they are mutable unless they are initialized with the Key
keyword.