2

Which ternary operator in C# is most popular and mostly used?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98

2 Answers2

16

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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
  • 49,681
  • 17
  • 108
  • 138