asp.net.ph

Skip Navigation LinksHome > Getting Started > ASP.NET Programming Languages Primer > The Conditional ? : Operator

ASP.NET Programming Languages Primer


C# and JScript include the conditional ? : operator, which executes one of two statements depending on a condition.

test ? statement1 : statement2

Key Points

  • 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." );
  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.";
  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.

Dynamic CheckBox Sample
Run Sample | View Source
Determining Selected Items in a CheckBoxList Control
Run Sample | View Source
DataGrid ShowHeader Property Example
Run Sample | View Source
Responding to Page and Control Events
Run Sample | View Source
WebControl Enabled Property Example
Run Sample | View Source
More ...
Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note