CSharp Coding Guidelines

From Direct Project
Jump to navigation Jump to search

Overview


When editing or adding code into an existing project, do try to follow the style already in place.

.NET Framework Design Guidelines A deep dive on how to build good .NET Frameworks.

Design Rules and Patterns


For classes with multiple constructors, use constructor chaining to consolidate business logic in one constructor.

Keep methods short and focused on one consistent operation.


Extension Methods


Implement extension methods in a class called Extension.

Generally, implement static methods in a [TODO]


Iteration

Use IEnumerable<T> functional extension methods for simple filters, searches or transforms.

//filter by a simple predicate MyCollection filtered = oldCollection.Where(x => x.foo == "Bar");


Use LINQ or foreach in preference to explicit for loops:

//Do this
var results = from x in oldCollection
                        where x.foo == "bar"
                        select new Baz(x.bux);
// or this
foreach( MyObject x in oldCollection)
{
// do some stuff
}
// not this
for(int i = 0; i < oldCollection.Length; i++)
{
    MyObject x = oldCollection[i];
}



API Documentation


All project files must build documentation XML in the build directory.

All public constructors, methods, properties and types must have XML documentation, even when the documentation is trivial or otiose. The expectation is that the documentation XML file will build without warning.

Use the <summary> tag in all cases, <param> and <returns> for methods and constructors, <exception> when exceptions are likely to be unavoidable in normal code paths. Use the <example> tag for the classes and methods most likely to be used by developers. Use the <value> tag for properties where the meaning of various property values is important to document.

Naming Conventions

  1. Classes and Interfaces:
    1. Names must begin with Upper Case
    2. Each Public class must be in its own file. File name must be same as class name.
    3. Folder Structure should mirror Namespace hierarchy
  2. Member variables:
    1. Must be prefixed with m_
    2. Must start with lower case, and use camel-casing
    3. E.g. m_incomingMessage
  3. Properties:
    1. Must begin with UpperCase and use camel casing subsequently
    2. E.g. MyStringProperty
  4. Variables
    1. Must begin with lower case and use camel casing subsequently
    2. E.g. int myVariableName
  5. Variable declarations must use explicit types; var should be used only when necessary (i.e. in LINQ or anonymous types, where it's impossible to use an explicit type declaration).
  6. When in doubt, follow the convention of the code already in place. We want the code to read with a consistent voice and not two or more authors.