C# Coding guidelines
In general, I follow the C# coding style used by the .NET team, which can be found at GitHub and Microsoft Docs.
There are with few additions and exceptions, however. Most of these come down to one thing: human readability. It is easy to write code that can be understood by compilers, but much more difficult to write code that can be easily understood by others (or future you).
Where possible, these conventions and guidelines are compiled into an .editorconfig file.
Unlike Microsoft, I strongly encourage the use of
var in all cases, even in
cases where it is not ‘apparent’ from context:
Don’t rely on the variable name to specify the type of the variable. It might not be correct. In the following example, the variable name
inputIntis misleading. It’s a string.
var inputInt = Console.ReadLine(); Console.WriteLine(inputInt);
The real problem here is not the type of the variable, but the name of the
variable. Changing the example to
string inputInt serves nothing but to hide
the underlying problem and add to the confusion. Instead, I recommend renaming
the variable to be more clear.
Additions to the C# coding style
- Use expression bodies for members when it only contains a single line or statement;
- Sort members in the following order:
- Fields, constructors/destructors, events, properties/indexers, methods, other nested types.
- In each group, sort
public staticmembers first, then
protected static, etc.
One of the most important, if not the most important aspects of readability is naming things. Naming things is hard. Here are a few pointers that could help:
Focus on the name itself. The length of a name is secondary. Your IDE will autocomplete it for you anyway.
Use XML documentation for anything that doesn’t fit in the name.
Do not simply repeat the name of the thing you’re documenting. Use this to add meaningful context, specific details or edge cases.