Black Lotus
Black Lotus

Reputation: 2397

When do I use curly brackets and when not?

Today they handed me over a old project someone has worked on for quite some time. Something I noticed was the inconsistency in when they use curly brackets and when not. So my question now is, are there any rules in when you use them and when not?

Little example of what I mean:

public int CompareTo(object obj)
    {
        BcFeedLeftOver other = obj as BcFeedLeftOver;
        if (other != null)
            return (_date.CompareTo(other.Date));
        else
            throw new ArgumentException("Object is not a BcFeedLeftover");
    }

This is the original function as you can see no use of curly brackets. But in a lot of other functions like this one he does use them, even if the if statement only executes 1 line of code like in the example above.

Upvotes: 2

Views: 572

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157116

You have to if your if statement spans multiple commands. If not, it is free to you to determine when to use it or not.

Some might find always adding curly brackets a good standard for readability or code safety, others don't and tend to only use them when they need to. It is totally up to you!

I tend to always use brackets. It is easier to mess up things if you don't add them. If you add them, you are always sure the body of the if statement works as expected and that adding a single line doesn't mess up everything.

Upvotes: 9

Related Questions