if ... else if ... else if ... else ... : an alternative

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).

http://www.blog.activa.be/2008/03/11/ifElseIfElseIfElseAnAlternative.aspx

你可能感兴趣的:(native)