Inline If Statement

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.

blog comments powered by Disqus