[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 892
  • Last Modified:

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

Please advise the VB.NT and C# code for doing the following:
condition ? exp1:exp2
Thanks
0
ksfok
Asked:
ksfok
  • 3
  • 2
1 Solution
 
vigylantCommented:
Look here:
http://csharptutorial.blogspot.com/2006/05/question-mark-ternary-operator.html

VB.NET has no ternary syntax similar to this...
0
 
vigylantCommented:
(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.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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.
0
 
vigylantCommented:
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 :)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now