?: Operator (C# Reference)
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0; s = x != 0.0 ? Math.Sin(x)/x : 1.0;
The conditional operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.
The conditional operator cannot be overloaded.
int yourInt = 5;
object someValue = condition ? yourInt : yourFloat;
This might not get you exactly what you expected; you would probably expect to get an int if 'condition' is true, and a float if 'condition' is false, but, the compiler will actually cast yourInt to a float -- resulting in someValue always being a float.
This particularly annoyed me, because I was using ToString() on it, which obviously wouldn't work out if I expected an int, but got a float instead (since the string representation is completely different).
I am just confused on which should be used when.
When should we use ?: and when should we use if() and which is better one.
Thanks,
Ajay Matharu
http://www.ajaymatharu.com
- 6/2/2009
- Ajay Matharu
- 6/2/2009
- Ajay Matharu