?: Operator (C# Reference)
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
Calculations that might otherwise require an if-else construction can be expressed more concisely and elegantly with the conditional operator. For example, to avoid a division by zero in the calculation of the sin function you could write either
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
or, using the conditional operator,
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
The conditional operator is right-associative, so an expression of the form
a ? b : c ? d : e
is evaluated as
a ? b : (c ? d : e)
not
(a ? b : c) ? d : e
The conditional operator cannot be overloaded.
Reference
C# Operatorsif-else (C# Reference)
Concepts
C# Programming GuideOther Resources
C# ReferenceEdit by SJ at MSFT: You can also get a simpler example in the current version of the topic, here: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx.
- 1/16/2012
- mikepope
- 2/6/2012
- SJ at MSFT
ValueToCheck == null ? ValueIfNull : ValueIfNotNull;
Sample:
var value = ViewState["AValue"];
MyTextbox.Text = (value != null) ? value .ToString() : String.Empty;
- 8/19/2010
- gbrusella
- 8/20/2010
- abatishchev
//Set our minimum and maximum limit values
int Min = 0;
int Max = 100;
//Perform three comparisons. One with value below the minimum, one with Value above the maximum
//and one with Value between the minimum and maximum
int A = MinMax(-2, Min, Max);
int B = MinMax(102, Min, Max);
int C = MinMax(25, Min, Max);
//Display the results
Console.WriteLine("Value of A: {0}", A, B, C);
Console.WriteLine("Value of B: {1}", A, B, C);
Console.WriteLine("Value of C: {2}", A, B, C);
private static int MinMax(int Value, int MinVal, int MaxVal)
{
//if Value is < MinVal, MinVal is returned.
//if Value is >= MinVal, compare Value to MaxVal
// if Value is > MaxVal, MaxVal is returned
// if Value is <= MaxVal, Value is returned
return Value < MinVal ? MinVal : (Value > MaxVal ? MaxVal : Value);
}
//Output
//Value of A: 0
//Value of B: 100
//Value of C: 25
- 8/18/2010
- TENware