Thursday, 9 September 2010

Constructor initialisors in VB.Net

Something very simple had me scratching my head again when I tried to remember how to do it in VB.Net, namely constructor initialisors.

So, take the following C# fragment with instantiates a member variable and populates it with some test data:

_data = new List<Core.Domain.Configuration>();
_data.Add(new Core.Domain.Configuration() { Key = "key1", Value = "value1" });
_data.Add(new Core.Domain.Configuration() { Key = "key2", Value = "value2" });
_data.Add(new Core.Domain.Configuration() { Key = "key3", Value = "value3" });

In VB.Net the equivalent is:

_data = New List(Of Core.Domain.Configuration)()
_data.Add(New Core.Domain.Configuration() With {.Key = "key1", .Value = "value1"})
_data.Add(New Core.Domain.Configuration() With {.Key = "key2", .Value = "value2"})
_data.Add(New Core.Domain.Configuration() With {.Key = "key3", .Value = "value3"})

Note the use of the With keyword and prefixing the property names with a dot.