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]
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");
It’s simple a ternary expression, it works in almost every language (C, Java, Py…) not only in C#.
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
You can also combine multiple.
Example:
return (idx==1 ? “yes” : ( idx > 1 ? “maybe” : “no”));
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