Which ternary operator in C# is most popular and mostly used?
+11
A:
The operator sometimes known as the ternary operator is actually named the conditional operator. It's of the form
A ? B : C
where A is a Boolean expression, and B and C are expressions either of the same type, or of types such that the type of B can be implicitly converted to the type of C or vice versa.
First A is evaluated; if the result is true
then B is evaluated to provide the result. Otherwise C is evaluated to provide the result.
Jon Skeet
2009-11-04 15:07:16
When did you change your name?
DrG
2009-11-04 15:09:42
Only you can get 7 upvotes in one minute on what was originally an incomprehensible question. ;)
AnthonyWJones
2009-11-04 15:10:07
At least, you have left the "why is popular" part unanswered to give the rest of us an opportunity :-)
Konamiman
2009-11-04 15:11:12
@DrG: http://meta.stackoverflow.com/questions/28192/has-jon-skeet-been-hacked/28194#28194
Konamiman
2009-11-04 15:13:14
+1
A:
It is popular because it leads to shorter and more readable code. Consider this simple example:
int daysInYear = isLeapYear ? 366 : 365;
instead of
if(isLeapYear) {
daysInYear = 366;
} else {
daysInYear = 365;
}
Konamiman
2009-11-04 15:10:18