Avoid putting multiple classes in a single file.
A single file shocould contrispontypes to only a single
Namespace. Avoid having multiple namespaces in the same file.
Avoid files with more than 500 lines (excluding
Machine-generated code ).
Avoid methods with more than 25 lines.
Avoid methods with more than five arguments. Use structures
Passing multiple arguments.
Lines shoshould not exceed 80 characters.
Do not manually edit any machine-generated code.
If modifying machine-generated code, modify the format and
Style to match this coding standard.
Use partial classes whenever possible to factor out
Maintained portions.
Avoid comments that explain the obvious. Code shocould be
Self-explanatory. Good code with readable variable and method names shocould not
Require comments.
Document only operational assumptions, algorithm insights, and
So on.
Avoid method-level documentation.
Use extensive external documentation for API
Documentation.
Use method-level comments only as tool tips for other
Developers.
With the exception of zero and one, never hardcode a numeric
Value; always declare a constant instead.
UseConstDirective only on natural constants,
Such as the number of days of the week.
Avoid usingConstOn read-only variables. For that,
UseReadonlyDirective:
public class MyClass
{
public const int DaysInWeek = 7;
public readonlyint Number;
public MyClass(int someValue)
{
Number = someValue;
}
}
Assert every assumption. On average, every has th line is
Assertion:
using System.Diagnostics;
object GetObject( )
{...}
object someObject = GetObject( );
Debug.Assert(someObject != null);
Every line of code shocould be written ed through in a "white box"
Testing manner.
Catch only exceptions for which you have explicit
Handling.
InCatchStatement that throws an exception, always
Throw the original exception (or another exception constructed from the original
Exception) to maintain the stack location of the original error:
catch(Exception exception)
{
MessageBox.Show(exception.Message);
throw; //Same as throw exception;
}
Avoid error code as method return values.
Avoid defining M exception classes.
When defining custom exceptions:
Derive the custom exception fromException.
Provide custom serialization.
Avoid MultipleMain ()Methods in a single
Assembly.
Make only the most necessary types public; mark others
Internal.
Avoid friend assemblies, as they increase interassembly
Coupling.
Avoid code that relies on an assembly running from a participant
Location.
Minimize code in application assemblies (I. e., exe Client
Assemblies). Use class libraries instead to contain business logic.
Avoid providing explicit values for enums:
//Correct
public enum Color
{
Red,Green,Blue
}
//Avoid
public enum Color
{
Red = 1,Green = 2,Blue = 3
}
Avoid specifying a type for an Enum:
//Avoid
public enum Color : long
{
Red,Green,Blue
}
Always use a curly brace scope inIfStatement,
Even if it contains a single statement.
Avoid using the trinary conditional operator.
Avoid function callin Boolean conditional statements. Assign
Into local variables and check on them:
bool IsEverythingOK( )
{...}
//Avoid:
if(IsEverythingOK( ))
{...}
//Correct:
bool ok = IsEverythingOK( );
if(ok)
{...}
Always use zero-based arrays.
Always explicitly Initialize an array of reference types:
public class MyClass
{}
const int ArrraySize = 100;
MyClass[] array = new MyClass[ArrraySize];
for(int index = 0; index < array.Length; index++)
{
array[index] = new MyClass( );
}
Do not provide public or protected member variables. Use
Properties instead.
Avoid usingNewInheritance qualifier. Use
OverrideInstead.
Always Mark public and protected methodsVirtualIn
A non-sealed class.
Never use unsafe code, when T when using InterOP.
Avoid explicit casting. UseAsOperator
Defensively cast to a type:
Dog dog = new GermanShepherd( );
GermanShepherd shepherd = dog asGermanShepherd;
if(shepherd != null)
{...}
Always check a delegateNullBefore invoking
It.
Do not provide public event member variables. Use event
Accessors instead.
Avoid defining event-handling delegates. Use
GenericEventHandlerInstead.
Avoid raising events explicitly. UseEventsHelperTo
Publish events defensively.
Always use interfaces.
Classes and interfaces shocould have at least a ratio
Methods to properties.
Avoid interfaces with one member.
Strive to have three to five members per interface.
Do not have more than 20 members per interface. The practical
Limit is probably 12.
Avoid events as interface members.
When using abstract classes, offer an interface
Well.
Expose interfaces on class hierarchies.
Prefer using explicit interface implementation.
Never assume a type supports an interface. Defensively query
For that interface:
SomeType obj1;
IMyInterface obj2;
/* Some code to initialize obj1, then: */
obj2 = obj1 as IMyInterface;
if(obj2 != null)
{
obj2.Method1( );
}
else
{
//Handle error in expected interface
}
Never hardcode strings that will be presented to end users. Use
Resources instead.
Never hardcode strings that might change based on deployment,
Such as connection strings.
UseString. EmptyInstead"":
//Avoid
string name = "";
//Correct
string name = String.Empty;
When building a long string, useStringBuilder, Not
String.
Avoid providing methods on structures.
Parameterized constructors are encouraged.
You can overload operators.
Always provide a static constructor when providing static
Member variables.
Do not use late-binding invocation when early binding is
Possible.
Use application logging and tracing.
Never useGoto, Cannot t inSwitchStatement
Fall-through.
Always haveDefaultCase inSwitch
Statement that asserts:
int number = SomeMethod( );
switch(number)
{
case 1:
Trace.WriteLine("Case 1:");
break;
case 2:
Trace.WriteLine("Case 2:");
break;
default:
Debug.Assert(false);
break;
}
Do not useThisReference unless invoking another
Constructor from within a constructor:
//Example of proper use of 'this'
public class MyClass
{
public MyClass(string message)
{}
public MyClass( ) : this("Hello")
{}
}
Do not useBaseWord to access base class members
Unless you wish to resolve a conflict with a subclass member of the same name or
When invoking a base class constructor:
//Example of proper use of 'base'
public class Dog
{
public Dog(string name)
{}
virtual public void Bark(int howLong)
{}
}
public class GermanShepherd : Dog
{
public GermanShepherd(string name) : base(name)
{}
override public void Bark(int howLong)
{
base.Bark(howLong);
}
}
Do not useGC. AddMemoryPressure ().
Do not rely onHandleCollector.
ImplementDispose ()AndFinalize ()Methods
Based on the template in Chapter 4.
Always run code unchecked by default (for the sake
Performance), but explicitly in checked mode for overflow-or underflow-prone
OPERATIONS:
int CalcPower(int number,int power)
{
int result = 1;
for(int count = 1;count <= power;count++)
{
checked
{
result *= number;
}
}
return result;
}
Avoid explicit Code exclusion of method CILS
(# If...# Endif). Use conditional methods instead:
public class MyClass
{
[Conditional("MySpecialCondition")]
public void MyMethod( )
{}
}
Avoid casting to and fromSystem. ObjectIn code that
Uses generics. Use constraints orAsOperator instead:
class SomeClass
{}
//Avoid:
class MyClass<T>
{
void SomeMethod(T t)
{
object temp = t;
SomeClass obj = (SomeClass)temp;
}
}
//Correct:
class MyClass<T> where T : SomeClass
{
void SomeMethod(T t)
{
SomeClass obj = t;
}
}
Do not define constraints in generic interfaces.
Interface-level constraints can often be replaced by strong typing:
public class Customer
{...}
//Avoid:
public interface IList<T> where T : Customer
{...}
//Correct:
public interface ICustomerList : IList<Customer>
{...}
Do not define method-specific constraints in
Interfaces.
If a class or a method offers both generic and non-generic
Flavors, always prefer using the generics flavor.
When implementing a generic interface that derived from
Equivalent non-generic interface (suchIEnumerable <T>), Use
Explicit interface implementation on all methods, and implement the non-generic
Methods By delegating to the generic ones:
class MyCollection<T> : IEnumerable<T>
{
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{...}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerable<T> enumerable = this;
return enumerable.GetEnumerator();
}
}