IIf Function in VB.NET

The IIf function in VB.NET is a useful tool for returning one of two objects based on the evaluation of an expression. It serves as a shorthand conditional operator, allowing developers to write more concise code when dealing with conditional logic.

IIf function

The IIf function is specific to VB.NET and is not available in other languages like C#. This is because the IIf function is part of the Visual Basic language and is not included in the Common Language Runtime (CLR) that underlies the .NET Framework. In C#, developers typically use the conditional operator (?:) as an equivalent construct to achieve similar functionality.

IIf(Expression As Boolean,TruePart As Object,FalsePart As Object) As Object

The IIf function provides an alternative to using the If...Then...Else statement in VB.NET. It takes three arguments: a Boolean expression, an object to return if the expression evaluates to True, and an object to return if the expression evaluates to False. Based on the evaluation of the expression, the IIf function returns one of the two objects.

Consider the following example :

If 10 > 9 Then MsgBox("True") Else MsgBox("False") End If

is same as:

MsgBox(IIf(10 > 9, "True", "False"))

Both statements returns True.

Note :The expressions in the argument list can include function calls.

The advantage of using the IIf function is that it allows for more compact and readable code compared to using the If...Then...Else statement in certain scenarios. However, it's important to note that the IIf function differs from the If...Then...Else statement in terms of execution flow. The IIf function evaluates both the true and false objects before returning the appropriate result, whereas the If...Then...Else statement evaluates only the branch that matches the condition.

Full Source VB.NET
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim value As Integer = 190 MsgBox(IIf(value > 100, "higher", "smaller")) ' The following If..Else..statements return the same result If value > 100 Then MsgBox("higher") Else MsgBox("smaller") End If End Sub End Class

Conclusion

Using the IIf function, VB.NET developers can write more concise and streamlined code when dealing with conditional expressions. It provides a convenient way to handle simple conditional scenarios where a choice needs to be made between two objects based on an expression's evaluation.