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
How should C# code look?
- Four spaces, no tabs. source
How are names written in C#?
| Kind | Example | Rule |
|---|---|---|
| Types | ShoppingCart | PascalCase for types, namespaces and public members. source |
| Functions | AddItem | PascalCase for types, namespaces and public members. source |
| Variables | itemCount | camelCase for arguments, locals and private fields. source |
| Constants | MaxItems | PascalCase for constants. source |
| Private fields | _itemCount | Private fields in camel case with a leading underscore. source |
What does cleaner C# look like?
class invoiceprinter : printable {
const int max_lines = 40;
private int count;
public void print_page(string t) { count++; Console.WriteLine(t); }
}class InvoicePrinter : IPrintable
{
private const int MaxLines = 40;
private int _pagesPrinted;
public void PrintPage(string text)
{
_pagesPrinted++;
Console.WriteLine(text);
}
}What changed?
Other languages
More on clean code: comments, functions, naming and the checklist.