Inline If Statement

Published on
-
1 min read

Standard IF statements are great. But I found that when I am using very simple conditions within my IF Statement I waste a lot of space in my code.

Example 1:

public int IfExample(bool bolFlag)
{
int result = 0;
if (bolFlag)
{
result = 1;
}
else
{
result = 2;
}
return result;
} 

There is no problem using Example 1. But there is a much quicker and less tedius way of using a simple conditional IF statement.

Example 2:

public int IfExample(bool bolFlag)
{
return (bolFlag) ? 1 : 2;
}

This example is basically saying: "return if (bolFlag) 1 else 2". So you are in theory assigning the IF condition to the variable.

I know it takes a little while to understand the syntax. But it is really good for those less complex IF conditions.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.