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.
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”));
Trackbacks