Link to home
Start Free TrialLog in
Avatar of ksfok
ksfok

asked on

VB.NET & C# syntax for "condition ? exp1: ext2"

Please advise the VB.NT and C# code for doing the following:
condition ? exp1:exp2
Thanks
ASKER CERTIFIED SOLUTION
Avatar of vigylant
vigylant

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vigylant
vigylant

(No edit function, so cant edit prev. post)

You can however do like this in VB.NET:

Dim var As Object = If(Condition, True, False)

If the condition is true, the true part (can be any object, not just a boolean) is returned, else the false part is returned.
Avatar of Mike Tomlinson
In vigylant's post, "If" should be "Iif".

Note that it has TWO I's.

It is also important to note that BOTH the true and false portions are completely evaluated regardless of the outcome of the "Condition" part.
No, that is wrong.
Microsoft.VisualBasic.IIf should not be used, because it contains functions for backwards compability only (With VB6), and slow ones at that.

Always disable the Microsoft.VisualBasic namespace import in your project settings, as all other methods are better/faster :)
The IF statement proposed by vigylant (that takes three arguments) is only available in VB.Net 2008.  Older versions have to use IIf.

See the old IIf: http://msdn.microsoft.com/en-us/library/27ydhh0d.aspx

    "Note: Visual Basic 2008 introduces a new If operator that uses short-circuit evaluation. For more information, see If Operator."

    "Because the IIf function does not use short-circuit evaluation, it always evaluates all three of its arguments."

Here is the newer If function (VB.Net 2008): http://msdn.microsoft.com/en-us/library/bb513985.aspx