views:

455

answers:

2

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
When did you change your name?
DrG
Only you can get 7 upvotes in one minute on what was originally an incomprehensible question. ;)
AnthonyWJones
At least, you have left the "why is popular" part unanswered to give the rest of us an opportunity :-)
Konamiman
@DrG: http://meta.stackoverflow.com/questions/28192/has-jon-skeet-been-hacked/28194#28194
Konamiman
+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
ok well done answer