Braces

General

Braces should be used to show code block ownership.
Don't:

  • Omit braces after conditionals or looping constructs.
  • Cram braces into one line statements. The one exception is for get and set statements.
  • Place braces on the same line as the preceding statement
  • Use braces inconsistently case blocks. (either use them for all case statements or none of them)

Examples

Good - following ALL the rules

public class BraceExamples 
{    
    public void DoSomeStuff(int x)
    {
        if (x > 0)
        {
            Console.WriteLine("X is greater than 0");
        }
        else if (x == 0)
        {
            Console.WriteLine("X is 0");
        }
        else
        {
            Console.WriteLine("X is less than 0");
        }
 
        if (x % 5) 
        { 
            Console.WriteLine("X is a factor of 5");
        }
        else
        {
            Console.WriteLine("X isn't a factor of 5");
        }
 
        switch (x) 
        {
            case 0: 
            {
                x++;
                x*1;
                x--;
                break;
            }
            case 1:
            {
                x = x + 0;
                break;
            }
        }
    }
}

Bad - breaking ALL the rules

public class BraceExamples {
 
    public void DoSomeStuff(int x) {
        if(x > 0)
            Console.WriteLine("X is greater than 0");
        else if(x == 0)
            Console.WriteLine("X is 0");
        else
            Console.WriteLine("X is less than 0");
 
        if(x % 5) { Console.WriteLine("X is a factor of 5") }
        else { Console.WriteLine("X isn't a factor of 5") }
 
        switch (x) {
            case 0: {
                x++;
                x*1;
                x--;
                break;
            }
            case 1:
                x = x + 0;
                break;                
        }
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.