Show Menu
Cheatography

C# coding standards Cheat Sheet (DRAFT) by

C# cheast sheteC# cheast sheteC# cheast shete

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Control Flow

Avoid changing a loop variable inside a for loop block.
Try to update loop variables close to where the loop condition is specified.
Always put a default label for switch statements
Avoid conditions with double negatives.

Object Lifecycle

Try to declare variables close to where they are used.
Try to initialize variables at the point of declar­ation.
Never shadow a name in an outer scope.
Avoid implem­enting a finalizer.
Avoid empty finali­zers.
Always implement IDispo­sable if a classes uses unmanaged resources or owns disposable objects.
Never call a virtual method unless the object is fully constr­ucted.

Exceptions

Never silently ignore except­ions.
Try to use standard except­ions.
Try to throw the most specific exception possible.
Always log when an exception is thrown. Log verbosely.
Always create verbose error messages.
Always list the explicit exceptions a method or property can throw.

General Guidelines

Always favor simpli­city. Write the simplest code that will work. KISS.
Always favor readab­ility. Name your variables and methods as clearly and as descri­ptively as possible.
Try to keep methods under 25 lines of code (excluding vertical spacing and comments). Break down your code into small functions that are easy to unders­tand. If a method is over 30 lines of code, it should be refact­ored.
Try to keep classes under 400 lines of code (excluding vertical spacing and comments). If a class is over 500 lines of code, it should be split out into separate classes that each do one thing.
Try to keep your code DRY, extract duplicate code into methods.
Try to include design­-pa­ttern names such as Bridge, Adapter, or Factory as suffix to class names where approp­riate.
Avoid duplic­ating constants. Separate into a config file.
Always delete unrefe­renced files.
Try to have lines less than 80 charac­ters. If the line exceeds 160 charac­ters, it should be refact­ored.
Never have more than two nested calls on the same line.
Never have methods with more than three levels of nesting.
Never have methods with more than five parame­ters. Try to have no more than three parameters at most being passed into a method, and generally only two.
Avoid having methods with out parame­ters.
Avoid having methods with ref parame­ters.
Avoid writing overloads for methods that you might use some day. Follow YAGNI principle.
Never progra­mma­tically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.
Never hardcode a path or drive name in code. Get the applic­ation path progra­mma­tically and use relative path.
Never assume that your code will run from drive "­C:". You may never know, some users may run it from network or from a "­Z:".
Always in the applic­ation start up, do some kind of "self check" and ensure all required files and depend­encies are available in the expected locations. Check for database connection in start up, if required. Give a friendly message to the user in case of any problems.
Always if a wrong value found in the config­uration file, applic­ation should throw an error or give a message and also should tell the user what are the correct values.
Always return empty collec­tions instead of null.
Always remove dead code.
Always remove unnece­ssary using statem­ents.
Filenames and directory names are Pascal­Case, e.g. MyFile.cs.
Where possible the file name should be the same as the name of the main class in the file, e.g. MyClas­s.cs.
In general, prefer one core class per file.
A maximum of one statement per line.
A maximum of one assignment per statement.
Indent­ation of 2 spaces, no tabs.
Column limit: 100.
No line break before opening brace.
No line break between closing brace and else.
Braces used even when optional.
Space after if/for­/while etc., and after commas.
No space after an opening parent­hesis or before a closing parent­hesis.
No space between a unary operator and its operand. One space between the operator and each operand of all other operators.
Where possible, group interface implem­ent­ations together.
Namespace using declar­ations go at the top, before any namesp­aces. using import order is alphab­etical, apart from System imports which always go first.
Modifiers occur in the following order: public protected internal private new abstract virtual override sealed static readonly extern unsafe volatile async.
For single line read-only proper­ties, prefer expression body properties (=>) when possible.
For everything else, use the older { get; set; } syntax.
 

Data Types

Never use magic numbers or magic strings. Use constants or enums.
Try to only use var when the type is very obvious.
Never compare floating point values using ==, !=, or Equals
Try to make all your variables and return values strongly typed.
Always use the decimal type for currency data. Floating point types can lead to incons­istent compar­isons and rounding.

Object Oriented Progra­mming

Always separate concerns. Separate User Interface Logic, Business Logic, Data Logic, into separate projects
Always create methods to do only 'one job'. Do not combine more than one job in a single method, even if those jobs are very small.
Always prefer compos­ition over inheri­tance.
Avoid Premature Genera­liz­ation. Create abstra­ctions only when the intent is unders­tood.
Avoid creating methods that function differ­ently based on the underlying type of the object.
Always declare all data members private.
Always prevent instan­tiation of a class if it contains only static members.
Always explicitly define a protected constr­uctor on an abstract base class.
Try to make all types internal by default.
Try to use using statements instead of fully qualified type names.
Never hide inherited members with the new keyword.
Always override the GetHas­hCode method whenever you override the Equals method.
Always override the Equals method whenever you implement the == operator, and make them do the same thing.
Always implement operator overlo­ading for the equality (==), not equal (!=), less than (<), and greater than (>) operators when you implement ICompa­rable
Always create variants of an overloaded method to be used for the same purpose and have similar behavior.
Always allow properties to be set in any order.
Never create a constr­uctor that does not yield a fully initia­lized object

Comments

Try to not check in commented code. Trust source control.
Always put comments in English.