Programming Blog

Jeremy Morgan

Mostly Coherent Ramblings of a Silicon Forest Software Developer

Using Ternary Operators in C#

By: Jeremy Morgan






Most people don’t use ternary operators enough, or at all. I think it’s a better way of handling such expressions most of the time. For example:

We have a small console app:

1
2
3
4
5
6
7
8
9
10
11
using System;
class Program
{
  static void Main()
  {
      for (int i = 1; i <= 10; i++)
      {
          Console.WriteLine(i);
      }
  }
}

This predictably outputs the numbers 1 through 10. But we’ll add some logic in here to identify even vs odd numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
class Program
{
  static void Main()
  {    
      for (int i = 1; i <= 10; i++)
      {
      string oddoreven;
      
          if (i % 2 == 0) {
          
              oddoreven = " even";
              
          }else {
          
              oddoreven = " odd";
              
          }
          Console.WriteLine(i + oddoreven);       
      }
  }

Ok, not terribly complicated, but if we use a ternary operator, we can turn 6 lines into one:

Instead of this:

1
2
3
4
5
6
string oddoreven;
  if (i % 2 == 0) {
      oddoreven = " even";
  }else {
      oddoreven = " odd";
  }

We now have this:

1
string oddoreven = (i % 2 == 0) ? " even " : " odd";

And the whole program looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
using System;
class Program
{
  static void Main()
  {
      for (int i = 1; i <= 10; i++)
      {
          string oddoreven = (i % 2 == 0) ? " even " : " odd";
          Console.WriteLine(i + oddoreven);       
      }
  }
}

See how much cleaner that is? If you have a file with tons of if-else statements you can save a ton of space by using ternary operators. Many folks say they’re harder to read but I just don’t see it. I think it’s much cleaner.

If you have more complicated conditional branching it doesn’t quite work as well but for many operations it does.

Note for the Newbies

This is a simple code optimization, but it doesn’t make your program any faster. Many new programmers automatically assume less code is faster running code, but that’s not always the case.

In this case the compiler will build the exact same IL, however the optimization is for the programmers. This is how you should be optimizing your code anyway. Let the compiler figure out how to save cycles and you make the code more readable and easy to understand.


Do you want to be notified every time a new tutorial is posted?

If you want to see more tutorials like these subscribe to our spam free newsletter and get them instantly in your inbox or feed reader. If you want to get all my updates, subscribe to the main RSS feed here.

Comments