Sunday, July 22, 2012

C# ?: Operator 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.

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.

class ConditionalOp
{
static double sinc(double x)
{
return x != 0.0 ? Math.Sin(x) / x : 1.0;
}

static void Main()
{
Console.WriteLine(sinc(0.2));
Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
}
}
/*
Output:
0.993346653975306
0.998334166468282
1
*/
 
source :msdn 

 

 

No comments:

Post a Comment