Question about the style of the code that we are writing

I am still relatively new to the world of coding, but I was wondering if there is an advantage to Nathan typing return after an if statement instead of putting the code in the if statement. An example of this is in the select method of Unit, he says:

public void Select()
    {
        if (!hasAuthority) return;
        
        
        onSelected?.Invoke();
    }

If I were to do it on my own, I would’ve said:

 public void Select()
    {
        if (hasAuthority)
        {
            onSelected?.Invoke();
        }
    }

Is there an advantage or is it just his coding style?

Hi Christian, good question.

This is really a preference. The advantage is it can be used as an exit statement. Anything below that return statement will not be called. You can do the same thing by putting all the remaining statements inside the if statement. Having the one line exit statement can be helpful for structuring the code and making it clearly to read. You also don’t have to keep track of where the if statement ends.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms