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.

var usage

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 inputInt is 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

Naming

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: