A shorter way for If statement in C#


July 17, 2009
There is no reason we shouldn't share our knowledge and experience. Please send me an article about IT, I will post it on my website, sure with a link back to your website. [More]

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");

Share
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”));

August 15th, 2011
Claudiu

You can also write code like this:

private void Foo(string bar)
{
// If bar is null, then set baz to “null”.
string baz = bar ?? “null”;
}

Trackbacks
Leave a Reply