Tuesday, November 27, 2012

Difference between IIF and If in VB.Net

In C# the conditional operator ‘?:’ works in a simple fashion and there is only one ternary operator. Early days of  VB.Net was too similar to C# as we had IIF function to achieve the same. But later they added a additional features to if keyword to behave like ternary conditional operator. That change mainly introduced an question into VB.Net interviews. What is the difference between IIF and if keyword.

‘IIF’ is a function which is available in Microsoft.VisualBasic.dll where the ‘if’ is a keyword which is part of the language. Simply speaking you can right click on the IIF and select “Go To Definition”.

IIF always accept 3 parameter. But if can accept 2 parameter. In that case the behavior will be changed in such a way that it returns second param if the first is null.Else the first parameter.

IIF evaluates all three parameter expressions (truepart and false part) regardless the value of first expression. But ‘if’ evaluates either second or third expression based on the value of the first expression.

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = IIf(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub
Public Function TruePart() As Boolean
Console.WriteLine("TruePart!")
Return True
End Function
Public Function FalsePart() As Boolean
Console.WriteLine("FalsePart!")
Return False
End Function

The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window
TruePart!
FalsePart!


Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = If(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub


The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window shows only
TruePart!

Want to learn more about other features of if keyword such as null alternate please visit the msdn link

No comments: