Tuesday, November 27, 2007

If Ternary Operator

This Article is first in the series of VB 9 articles. In this article I'll introduce you to the If Ternary Operator which the VB language lacks in its previous versions. You as a VB Programmer some how familiar with the Iif function or 'Immediate If'. The syntax of 'If Ternary Operator' is the same as compared to Iif i.e. Iif(Boolean,True,False) and you use it this way:

Dim
Amount As Integer = 100
Dim
ASign As Integer = Iif(Amount < 0, -1, 1)

When you execute the code the Iif function checks the condition, if the value of 'Amount' is greater than 'zero' it will return '1' otherwise '-1' pretty basic but what's the problem? actually the problem is that as it is a function which belongs to some library not a built-in operator or function of VB language therefore in VB all of the arguments evaluates before execution. Look at the following example:

Sub Main()

Dim Amount As Integer = 100
Dim ASign As Integer = IIf(Amount < 0, Negative, Positive)
Console.WriteLine(ASign)
Console.ReadLine()

End Sub

Function Negative() As Integer
MsgBox("In Negative Function")
Return -1
End Function

Function Positive() As Integer
Return 1
End Function

Although we are only interested in the Positive Funtion but as it's a function it will evaluate all the arguments here is the output of this code:



Therefor, Iif is not equal to the following code:

Dim Amount As Integer = 100
If i < 0 Then
Negative()
Else
Positive()
End If

But now we have the solution in VB in spite of writing the above code the same objective can be accomplished with the help of 'If Ternary Operator':

Dim Amount As Integer = 100
Dim Asign As Integer = If(Amount < 0, Negative, Positive)

And also look at the following code example:

Dim CustomerName As String = Nothing
Dim Value As String = If(CustomerName, "Not Set")

Actually the above code is equivalent to the following Code:

Dim CustomerName As String = Nothing
Dim Value As String = If(CustomerName IsNot Nothing, name, "Not Set")

Hope you get the idea of this powerful operator.

Good Luck !

1 comment:

Asad Naeem said...

Excellent. Very helpful article. Keep on writing to server the IT community.