Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Ternary conditional operator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Visual Basic=== [[Visual Basic]] doesn't use {{code|?:}} per se, but has a very similar implementation of this shorthand {{code|if...else}} statement. Using the first example provided in this article, it can do: <syntaxhighlight lang="vbnet"> ' variable = IIf(condition, value_if_true, value_if_false) Dim opening_time As Integer = IIf((day = SUNDAY), 12, 9) </syntaxhighlight> In the above example, {{code|IIf}} is a ternary function, but not a ternary operator. As a function, the values of all three portions are evaluated before the function call occurs. This imposed limitations, and in Visual Basic .Net 9.0, released with Visual Studio 2008, an actual conditional operator was introduced, using the {{code|If}} keyword instead of {{code|IIf}}. This allows the following example code to work: <syntaxhighlight lang="vbnet"> Dim name As String = If(person Is Nothing, "", person.Name) </syntaxhighlight> Using {{code|IIf}}, {{code|person.Name}} would be evaluated even if person is [[null pointer|{{code|null}}]] (Nothing), causing an [[exception handling|exception]]. With a true short-circuiting conditional operator, {{code|person.Name}} is not evaluated unless person is not {{code|null}}. [[Visual Basic .NET|Visual Basic]] Version 9 has added the operator {{code|If()}} in addition to the existing {{code|IIf()}} function that existed previously. As a true operator, it does not have the side effects and potential inefficiencies of the {{code|IIf()}} function. The syntaxes of the tokens are similar: {{code|If([condition], op1, op2)}} vs {{code|IIf(condition, op1, op2)}}. As mentioned above, the function call has significant disadvantages, because the sub-expressions must all be evaluated, according to Visual Basic's [[evaluation strategy]] for function calls and the result will always be of type variant (VB) or object (VB.NET). The {{code|If()}}operator however does not suffer from these problems as it supports conditional evaluation and determines the type of the expression based on the types of its operands.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)