cleancode.in

Clean code in C#

Microsoft’s C# conventions: PascalCase for types, methods and constants, camelCase for locals and parameters, an underscore before private fields, I before an interface name, 4 spaces a level and every brace on a line of its own.

What does Microsoft’s C# conventions ask for?

  • When naming an interface, use pascal casing in addition to prefixing the name with an I. source

From Microsoft Learn, C# naming.

How should C# code look?

What else does it ask?

  • Meaningful, descriptive names. source
  • No abbreviations but the well known. source
  • Braces on their own lines (Allman). source
  • One statement a line. source
  • Specific exception types. source

How are names written in C#?

KindExampleRule
TypesShoppingCartPascalCase for types, namespaces and public members. source
FunctionsAddItemPascalCase for types, namespaces and public members. source
VariablesitemCountcamelCase for arguments, locals and private fields. source
ConstantsMaxItemsPascalCase for constants. source
Private fields_itemCountPrivate fields in camel case with a leading underscore. source

What does cleaner C# look like?

Before
class invoiceprinter : printable {
    const int max_lines = 40;
    private int count;
    public void print_page(string t) { count++; Console.WriteLine(t); }
}
After
class InvoicePrinter : IPrintable
{
    private const int MaxLines = 40;
    private int _pagesPrinted;

    public void PrintPage(string text)
    {
        _pagesPrinted++;
        Console.WriteLine(text);
    }
}

What changed?

  • The class and its public method in PascalCase. source
  • The interface name starts with I. source
  • The constant in PascalCase, the private field in camelCase after an underscore. source
  • Braces on their own lines, one statement a line. source
  • count became _pagesPrinted: it says what is counted. source