C# If Else proper "do nothing" syntax

Viewed 19102

I am fairly new to programming and in my most recent work I created the following if else statement nested within a for loop:

for (int i = 0; i < originalColumnCells.Count; i++)
{
    if (originalColumnCells[i] == sortedColumnCells[i])
    {
        // Do Nothing
    }
    else
    {
        return false;
    }
}

In the if statement, as you can see, I want the method to do nothing if the statement is true. In this case, is it proper syntax to comment out "// Do Nothing", or should I leave it as open and closed braces? Or maybe put the braces at the end of the if line?

Any suggestions on the "right" way to handle this would be appreciated

4 Answers

Why not negate the expression?

for (int i = 0; i < originalColumnCells.Count; i++)
{
    if (originalColumnCells[i] != sortedColumnCells[i])
    {
        return false;
    }
}

Change the if statement to != and remove the else all together:

if (originalColumnCells[i] != sortedColumnCells[i])
{
   return false;
}
// No else

In general, you want to explain things that are unusual.

{

}  

Is this supposed to be empty? Did something get deleted? Better to make your intent explicit:

{
    // do nothing
}  

But -- also in general -- you probably want to change your if statement so you don't end up with empty statements. I see several answers saying to change the comparison from == to !=. However, what about some statement like

if (a > b && c == d || Object.ReferenceEquals(null, e)) ...  

In order to invert this, you would change > to <=, change == to !=, change && and || operators, etc. I find it simplest to just invert the entire statement with ! instead of trying to change each comparison operator:

if (!(a > b && c == d || Object.ReferenceEquals(null, e))) ...  

You can inverse the statement:

if (originalColumnCells[i] != sortedColumnCells[i])

But then something else. Sometimes you want indicate you have thought about the need of an else branch but you don't need one. (I sometimes want one if I have larger code blocks with complex statements) Then it is fine in my opinion to use something along these lines:

else
{
    // no action, already handled later on in bla bla
}
Related