The Grayzone

VB.NET Object Initializer and Single Line If Statements

I’ve recently started working at a company that has quite a few VB.NET application sitting around, and as you can see from the rest of my posts I’m used to using C#

A couple of C# language features that I use a lot are Object Initializers and single line if statements. This might be old news to some of you but I finally discovered how to implement these two features in VB.NET. Both of the following features were introduced in VB.NET 9.0 (.NET 3.5).

Object Initializers

Take the following object initializer in C#

Person p = new Person
{
  Name = "Peter Piper",
  Age = 20
};

This can be replicated in VB.NET using the With keyword.

Dim p As New Person() With {.Name = "Peter Piper", .Age = 20}

Single Line If statement

To keep code clean and neat I often use the following syntax in C# (and Javascript) for single line If statements (Ternary operators):

string name = person == null ? string.Empty : person.Name;

The VB.NET equivalent of this was introduced in VB.NET 9.0 and superceded the IIF function which evaluates all 3 parts of the function before calling it because it was a function rather than a tertiary operator.

Dim name As String = If(person Is Nothing, String.Empty, person.Name)


Share this: