Вы находитесь на странице: 1из 3

Coding Guidelines for C# 3.0 and C# 4.

0 Cheat Sheet
Design
Basic Principles The Principle of Least Surprise Keep It Simple Stupid You Aint Gonna Need It Dont Repeat Yourself

Member Design
Allow properties to be set in any order Avoid mutual exclusive properties (SCC1110) A method or property should do only one thing Return an IEnumerable<T> or ICollection<T> instead of a concrete collection class (SCC1130) String, list and collection properties should never return a null reference Avoid method with more than 5 parameters, use structures for multiple parameters. Mark only the most necessary type as public directive else all others should be internal.

of a try block. Its done automatically when a using statement is used. Never present debug information to yourself or the end user via the UI (e.g. MessageBox). Use tracing and logging facilities to output debug information. Group all framework namespaces together and 3rd party or custom namespaces underneath. Always use zero-based arrays. Always use zero-based indexes with indexed collections

Class Design
A class or interface should have a single purpose (SCC1000) An interface should be small and focused (SCC1003) Dont hide inherited members with the new keyword (SCC1010) It should be possible to treat a derived object as if it were a base class object (SCC1011) Dont refer to derived classes from the base class Avoid exposing the objects an object depends on (SCC1014) Avoid bidirectional associations Classes should have state and behavior (SCC1025) Use a separate file for each class, struct, interface, enumeration and delegate with the exception of those nested within another class Write comments first. When writing a new method, write the comments for each step the method will perform before coding a single statement. These comments will become the headings for each block of code that gets implemented.

Miscellaneous Design
Throw exceptions rather than returning status values Dont swallow errors by catching generic exceptions (SCC1210) Dont pass null as the sender parameter when raising an event (SCC1235) Use generic constraints if applicable (SCC1240) Dont add extension methods to the same namespace as the extended class Evaluate the result of a LINQ expression before returning it Use the StringBuilder class and its Append(), AppendFormat(), and ToString() methods instead of the string concatenation operator (+=) for much more efficient use of memory. Be sure Dispose() gets called on IDisposable objects that you create locally within a method. This is most commonly done in the finally clause

CSharpCheatSheet

January 4, 2011

Coding Guidelines for C# 3.0 and C# 4.0 Cheat Sheet


Maintainability
Maintainability
Methods should not exceed 7 statements (SCC1500) Make all members private and types internal by default (SCC1501) Avoid conditions with double negatives (SCC1502) Dont use "magic numbers" (SCC1515) Only use var when the type is very obvious Initialize variables at the point of declaration Favor Object and Collection Initializers over separate statements (SCC1523) Dont make explicit comparisons to true or false (SCC1525) Dont change a loop variable inside a for or foreach loop Dont use nested loops in a method Add a block after all flow control keywords, even if it is empty (SCC1535) Always add a default block after the last case in a switch statement Finish every if-else-if statement with an else-part Be reluctant with multiple return statements (SCC1540) Prefer conditional statements instead of simple ifelse constructs (SCC1546) Encapsulate complex expressions in a method or property Call the most overloaded method from other overloads Use optional parameters to replace overloads only Avoid using named parameters Avoid methods with more than three parameters Dont use ref or out parameters (SCC1562) Avoid methods that take a bool flag (SCC1564) Always check the result of an as operation for null Dont comment-out code Never hard code magic values into code (strings or numbers). Instead, define constants, static read-only variables, and enumerations or read the values from configuration or resource files.

Framework Guidelines
Use C# type aliases instead of the types from the System namespace (SCC2201) Build with the highest warning level Use Lambda expressions instead of delegates (SCC2221) Only use the dynamic keyword when talking to a dynamic object (SCC2230)

CSharpCheatSheet

January 4, 2011

Coding Guidelines for C# 3.0 and C# 4.0 Cheat Sheet


Naming & Layout
Naming
Do use proper US English Dont include numbers in identifiers Dont prefix member fields (SCC1705) Dont use abbreviations Name an identifier according its meaning and not its type Name types using nouns, noun phrases or adjective phrases (SCC1708) Dont repeat the name of a class or enumeration in its members Avoid short names or names that can be mistaken with other names Name methods using verb-object pair (SCC1720) Upper Casing Abbreviations ID, REF Always put opening and closing parentheses on a new line. Dont indent object Initializers and initialize each property on a new line. Dont indent lambda statements Put the entire LINQ statement on one line, or start each keyword at the same indentation.

Documentation
Do not put comments on obvious code. Code should be self-explanatory. Good code with readable variable and method names should not require comments. Insert code comments on Classes and Class members which implement functionality or encapsulate multiple methods that do not obviously describe the intent of the code. When deciding if a code comment is necessary, lean toward adding a code comment to make the code sufficiently clear to a developer Add comments with the intent of describing the functionality to a developer new to the technology and project that will be maintaining and understanding the code Use /* */ only for temporary comments Mark incomplete code with // TODO: comments. When working with many classes at once, it can be very easy to lose train of thought. The solutions leads will be reviewing for comments.

Add braces around comparison conditions, but dont add braces around a singular condition. Regions only for Private fields and constants Nested classes Interface implementations (only if its not the main purpose of the class) Empty lines Between members After the closing parentheses Between multi-line statements Between unrelated code blocks Around the #region keyword Between the using statements of different companies. Member order 1. Private fields and constants 2. Public constants 3. Public read-only static fields 4. Constructors and the Finalizer 5. Events 6. Properties 7. Other members grouped in a functional manner. 8. Private properties Other private methods in calling order in-line with public methods.

Pascal Casing Class, Struct Interface Enumeration type Enumeration values Event Protected field Const field Read-only static field Methods Namespace Property Type Parameter Variables(public) NameSpaces Camel Casing Private field Variables(non-public) Const variable Parameter

AppDomain IBusinessService ErrorLevel FatalError Click MainPanel MaximumItems RedValue ToString System.Drawing BackColor TEntity WindowSize SCC.Data.DataAccess

Layout
Maximum line length is 130 characters. Indent 4 spaces, dont use Tabs Keep one whitespace between keywords like if and the expression, but dont add whitespaces after ( and before ). Add a whitespace around operators, like +, -, ==, etc. Always add parentheses after keywords if, else, do, while, for and foreach

listItem listOfValues maximumItems typeName

CSharpCheatSheet

January 4, 2011

Вам также может понравиться