Like many tips & tricks concerning programming languages, what I will present here will be so utterly obvious to some C# developers, but could be an eye-opener to others.

How often do you write something like this?

if (token == "A")
   tokenNumber = 1;
else if (token == "B")
   tokenNumber = 4;
else if (token == "C")
   tokenNumber = 5;
else if (token == "X")
   tokenNumber = 10;
else
   tokenNumber = 20;

How about writing it like this?

tokenNumber = (token == "A") ? 1:
              (token == "B") ? 4:
              (token == "C") ? 5:
              (token == "X") ? 10:
                               20;

It’s the same thing, but it looks cleaner, and the generated IL code is almost the same (it’s even a bit shorter).

The reason this works is because the ternary operator (?:) is one of the few right-associative operators in C#. The other 2 are the assignment operator (=) and the lambda operator in C# 3.0 (=>)