We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

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

Medium Priority
915 Views
Last Modified: 2013-12-17
Please advise the VB.NT and C# code for doing the following:
condition ? exp1:exp2
Thanks
Comment
Watch Question

Commented:
Look here:
http://csharptutorial.blogspot.com/2006/05/question-mark-ternary-operator.html

VB.NET has no ternary syntax similar to this...

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Commented:
(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.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
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.

Commented:
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 :)
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
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
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.