C# and JScript include the conditional ? : operator, which executes one of two statements depending on a condition.
test ? statement1 : statement2
- test can be any valid Boolean expression ( evaluates to true or false ).
- statement1 is the statement to be executed if test is true. May be a compound statement.
- statement2 is the statement to be executed if test is false. May be a compound statement.
A conditional expression of the form A ? B : C
first evaluates the condition A. Then, if A is true, B becomes the result of the operation. Otherwise, C becomes the result of the operation. A conditional expression never evaluates both B and C.
The test expression of the ? : operator must be an expression of a type that can be implicitly converted to bool ( returns either true or false ). If not, a compile-time error occurs.
The ? : operator is, in a way, a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward. For example:
DateTime now = DateTime.Now;
String greeting = "Good" + ( ( now.Hours > 17 ) ? " evening." : " day." );
var now = new Date ( );
var greeting = "Good" + ( ( now.getHours ( ) > 17 ) ? " evening." : " day." ); |
|
C# |
VB |
The example creates a string containing "Good evening" if it is after 5pm. The equivalent code using an if...else statement would look as follows:
DateTime now = DateTime.Now;
String greeting = "Good";
if ( now.Hour > 17 )
greeting += " evening.";
else
greeting += " day.";
var now = new Date ( );
var greeting = "Good";
if ( now.getHours ( ) > 17 )
greeting += " evening.";
else
greeting += " day."; |
|
C# |
VB |
The following example demonstrates using the conditional operator.
Show me
Below are links to further code examples that illustrate using the conditional operator in ASP.NET web forms.