Tuesday, June 29, 2010

Ternary operator in VB.Net

If you are looking for ternary operator in VB.NET similar to C++,C#, Javascript etc if(expression?truepart:falsepart) then let me tell you that VB.NET offers a similar function to do that

you can write

Dim displayName As String = "FirstName"
Dim myName As String = IIf((displayName = "FirstName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Abhishek"
 myName = IIf((displayName = "SurName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Tiwari"

Please note that IIf is just a function which takes first input as an expression, evaluate it and return second input (if expression is evaluated to true) or return third input (if expression is evaluated to false).

There is a gotcha in using IIf function, it works little bit differently than ternary operator in C#. It basically evaluates both input (irrespective of expression evaluating to true or false). In Other languages, expression will be evaluated first and then based on the result other inputs will be evaluated.

for e.g.

Dim dict As New Dictionary(Of String, String)
Dim d = IIf(dict.ContainsKey("A"), dict("A"), Nothing)

will result in "KeyNotFound" exception although someone will assume that it should return Nothing without throwing exception.

Fortunately VB.Net 9 provides conditional operator (If) to be used as ternary operator too and it works exactly the same way the ternary operator works in C# or other language.


Dim dict As New Dictionary(Of String, String)
Dim d = If(dict.ContainsKey("A"), dict("A"), Nothing)

Note that I have used "If" instead of function "IIf" and later one will execute successfully and return Nothing without throwing any exception.

No comments:

Post a Comment