A shorter way for If statement in C#


July 17, 2009
Don't know what to read next? Check out the list of popular posts. People like them, they should be good.

another tip »

Instead of writing:

        if (idx == 1)
        {
            result = "Yes";
        }
        else
        {
            result = "No";
        }
        return result;

You could wrap it in one single line code

return ((idx == 1) ? "Yes" : "No");
  • Delicious

Some more useful articles for you

Under Category: C#.NET Code
Article
July 23rd, 2009
mux0x55

It’s simple a ternary expression, it works in almost every language (C, Java, Py…) not only in C#. :)

July 23rd, 2009

Yeap, I have a very bad memory and I’m not using this a lot so I’m keep forgoting it :( . Write a post here so when I need I could search for it easier :)

August 7th, 2009
Adao Santos

You can also combine multiple.

Example:
return (idx==1 ? “yes” : ( idx > 1 ? “maybe” : “no”));

Trackbacks
Leave a Reply