Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Difference between If and IIF? In which case, IIF condition is used and If condition is used? Why we use IIF in VB.NET?
Posted
Updated 11-Jan-15 21:28pm
v2

This has been removed in newer versions. I would recommend making use of If-Else or case construct. To know what iif does, take a look here[^].

Basically it does something like this:

iif([someCondition],[returnValueIfConditionIsTrue],[returnValueIfConditionIsFalse])
 
Share this answer
 
v3
Comments
Maciej Los 12-Jan-15 4:20am    
+5
Well. IIF is compatibility from VB6
better use IF instead, its more powerful, better, etc.

Why I use it? it makes code shorter
Example
VB
Dim this As Boolean = False
Console.WriteLine(If(this, "Yes", "No"))
 
Share this answer
 
I'd say: do not use Iif[^] function, which returns one of two objects, depending on the evaluation of an expression. Why? There is much, much better programming practice to use lambda expressions:
VB
Dim boolVal as Boolean = False

Dim result = Function(x As Boolean) As String
             Dim sRetVal as String = "yes"
                Select Case x
                    Case true
                        sRetVal = "yes"
                    Case False
                        sRetVal = "no"
                End Select
                Return sRetVal
                End Function

Console.WriteLine("The result is: {0}", result(boolval))


Above example is very simple. You may say that it's much easier to use iif or even if function (as is mentioned in answers to this question). It's true, but using lambda expressions is more flexible, because provides a way to create custom function that verifies condition and returns result as you define it.

For further information, please see: How to: Create a Lambda Expression (Visual Basic)[^]

By The Way, C# is more powerfull! Above Vb.Net code we can write as:
C#
string result = boolVal==true ? "yes" : "no";
Console.WriteLine("The result is: {0}, result);


Cheers,
Maciej
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900