博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2008-03-11 23:28  阿布  阅读(498)  评论(0编辑  收藏  举报

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