C# contains a single operator that handles conditional logic in a single statement. It is generally written as "?:" (making it difficult to find using a search engine) and it is often referred to as the conditional operator, although the official documentation does not give it this name.

I write about it here, not because it is new or extra cool, but because I believe it is underused by C# developers.

The syntax is:
condition ? ValueIfTrue : ValueIfFalse;

where

  • condition is a boolean expression to test
  • ValueIfTrue is the value to return if the condition expression is true
  • ValueIfFalse is the value to return if the condition expression is false

An example should clarify this:

   1: int x;
   2: string y;
   3: x = 1;
   4: y = x >= 0 ? "Positive" : "Negative";
   5: Console.WriteLine(y); 
   6:  
   7: x = -1;
   8: y = x >= 0 ? "Positive" : "Negative";
   9: Console.WriteLine(y); 

The output of this code snippet is:

Positive
Negative

The expression

x >= 0 ? "Positive" : "Negative";

returns the string "Positive" if x is at least 0 and "Negative" if x is less than 0.

Of course the same expression could be written like the following:

   1: x = 1;
   2: if (x >= 0)
   3: {
   4:     y = "Positive";
   5: }
   6: else
   7: {
   8:     y = "Negative";
   9: }
  10: Console.WriteLine(y);
  11: 
  12: x = -1;
  13: if (x >;= 0)
  14: {
  15:     y = "Positive";
  16: }
  17: else
  18: {
  19:     y = "Negative";
  20: }
  21: Console.WriteLine(y);

But this requires more typing (which provides more changes for errors); and (more importantly), it takes more time to read, so it cannot be digested as quickly by someone reviewing the code later. Of course, I'm assuming that the code reviewer is familiar with this operator, but I don't think that's an unreasonable expectation, given that it has been in the C# language over 10 years.

Many developers are not familiar with ?: operator, but they should be. It simplifies code and makes it easier to read.


Here is the full code of a console application demonstrating these concepts:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         int x;
   6:         string y;
   7:         x = 1;
   8:         y = x >= 0 ? "Positive" : "Negative";
   9:         Console.WriteLine(y);
  10: 
  11:         x = -1;
  12:         y = x >;= 0 ? "Positive" : "Negative";
  13:         Console.WriteLine(y);
  14: 
  15:         x = 1;
  16:         if (x >;= 0)
  17:         {
  18:             y = "Positive";
  19:         }
  20:         else
  21:         {
  22:             y = "Negative";
  23:         }
  24:         Console.WriteLine(y);
  25: 
  26:         x = -1;
  27:         if (x >;= 0)
  28:         {
  29:             y = "Positive";
  30:         }
  31:         else
  32:         {
  33:             y = "Negative";
  34:         }
  35:         Console.WriteLine(y);
  36: 
  37:         Console.ReadLine();
  38:     }
  39: }