VB equivalent of the C# ? operator

In C# you can quickly do if statements by using the ‘?’ operator, and check for null values by using the ‘??’ operator.

This is done with the following syntax:

int i = 1;
string result;
i > 1 ? result = "i is greater than one" : result = "i is one or less";

The same shorthand coding style can be achieved in VB.Net (since 2008) by using the IIf function as follows:

Dim i as Integer? = 1
Dim result as String
' C# '?' equivalent
IIf(i > 1, result = "i is greater than one", result = "i is one or less")
' Or C# '??' equivalent
IIf(i is nothing, result = "i is null!", result = "i is a number")

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>