A mostly reasonable approach to C#.
TIP: Use the .editorconfig file to maintain consistency
Use var to avoid redundant reputation of type names and simplify generic code.
DO:
var age = GetAge();DON'T:
int age = GetAge();Use comments sparingly and only when there is unusual behaviour that needs explanation; focus on the why and what of a code block and not the how.
Avoid line-by-line commentary; code should be self-documenting and easy for other developers to understand. Comments simply get in the way of reading code, add an unnecessary overhead during refactoring, and very easily fall out-of-date.
internal class Worker
{
private readonly IDependency _dependency;
private int _counter;
public bool SomeProperty { get; init; }
public Worker(IDependency dependency)
{
_dependency = dependency;
_counter = 0;
}
public void DoSomething()
{
_counter++;
DoSomethingElse();
}
private void DoSomethingElse()
{
_dependency.SomethingElse();
Log.Information("Counter is set to {counter}", _counter);
}
}- Private fields
- Public properties
- Constructors
- Public methods
- Private methods
For simplicity and code navigation only define one class per file.
An exception to this is the expansion into generics.
DO:
// Result.cs
namespace Helpers
{
internal class Result
{ }
internal class Result<TData> : Result
{ }
}DON'T:
// Result.cs
namespace Helpers
{
internal class Result
{ }
internal class Result<TData> : Result
{ }
internal class ResultError
{ }
internal class Retry
{ }
}Remove any unused using statements from the top of each file.
DO:
using System;
namespace Foo
{
internal class Bar
{ }
}DON'T:
namespace Foo
{
using System;
internal class Bar
{ }
}using System;
using System.Threading.Tasks;
using Bar;
using Foo;
using Foo.Baz;MyFile.cspublic class MyClass {...}public class Foo
{
public void MyMethod() {...}
}public class Foo
{
public int MyProperty { get; set; }
}public class Foo
{
private int _myField;
}public void Foo(int myParameter) {...}public void Foo()
{
var myVariable = 413;
}public class Foo
{
private const string MY_CONSTANT = "*screams*";
}The compiler and IDE can provide type information, prefixing this information is redundant and gets in the way of reading the code.
DO:
var username = "batman";DON'T:
var strUsername = "batman";For simplicity and code navigation keep the class name and the file name the same.
For simplicity and code navigation keep the namespace declaration consistent to the folder structure.