By Lance Hunt
By Lance Hunt
By Lance Hunt
.
Lance Hunt C# Coding Standards
License
Usage & Distribution
This work is FREE for educational and non-commercial use. Non-commercial redistribution of the work is
permitted so long as all license and all copyright notices are retained and respected. Commercial redistribution
of the work or derivative of the work in any form is prohibited unless prior permission is obtained from the
copyright holder.
Trademarks
All uses of terms that are known trademarks or service marks have been appropriately capitalized. The
Publisher cannot attest to the accuracy of this information. Use of terms within this work should not be regarded
as affecting the validity of any trademark or service mark. All Trademarks are the property of their respective
owners.
Disclaimer
The information provided is on an “As-Is” basis. The Author and Publisher shall have neither liability nor
responsibility to any person or entity with respect to the loss or damages arising from the information contained
in this work. This work may include inaccuracies or typographical errors and solely represent the opinions of the
Author. Changes are periodically made to this document without notice.
Any action related to this work will be governed by Texas law and controlling U.S. federal law. No choice of law
rules of any jurisdiction will apply.
The Author reserves the right to revise these terms at any time without notice.
Revision History
Version Date Comment
1.0 03/01/2004 Created.
1.01 05/09/2004 Added more Language Usage.
1.02 05/09/2004 Added code examples.
1.03 05/09/2004 Changed formatting and organization.
1.04 05/09/2004 Misc. grammar and syntax changes.
1.05 05/10/2004 Updated Naming Conventions.
1.06 05/10/2004 Misc. adjustments to various rules.
1.07 05/11/2004 Added Bibliography, Resources, and .NET Framework Guidelines.
1.08 05/20/2004 Split .NET guidelines into separate document.
Changed overall scope and goals. Restructured sections. Improved Introduction.
Added Scope and Terminology sections.
1.09 05/23/2004 Changed style & formatting. Added Quick Summary tables. Added/modified
various standards.
1.10 05/25/2004 Modified naming conventions for Internal and Protected identifiers. Added,
modified, & removed misc rules. Corrected grammar, code, and some verbiage.
1.11 06/08/2004 Modified formatting. Restructured “Language Usage” section. Corrected
language, and added code examples. Consolidated conflicting rules.
1.12 06/30/2004 Modified code commenting and formatting rules. Modified various code examples.
Modified Exception Handling and Flow Control sections.
1.13 08/17/2004 Modified layout & added License Agreement. Misc. grammar adjustments.
Removed rules on foreach vs for pending additional research. Added rules on
switch/case statements.
Table of Contents
1. Introduction ....................................................................................................................................................... 1
1.1 Scope ......................................................................................................................................................... 1
1.2 Document Conventions .............................................................................................................................. 1
1.3 Terminology & Definitions .......................................................................................................................... 2
1.4 Quick Summary.......................................................................................................................................... 3
1.4.1 Naming Conventions ......................................................................................................................... 3
1.4.2 Coding Style ...................................................................................................................................... 3
1.4.3 Language Usage ............................................................................................................................... 4
2. Naming Conventions ........................................................................................................................................ 4
2.1 General Guidelines..................................................................................................................................... 4
2.2 Name Usage & Syntax ............................................................................................................................... 5
3. Coding Style...................................................................................................................................................... 8
3.1 Formatting .................................................................................................................................................. 8
3.2 Code Commenting ..................................................................................................................................... 9
4. Language Usage............................................................................................................................................... 9
4.1 General....................................................................................................................................................... 9
4.2 Variables & Types .................................................................................................................................... 10
4.3 Flow Control ............................................................................................................................................. 11
4.4 Exception Handling .................................................................................................................................. 12
4.5 Events, Delegates, & Threading .............................................................................................................. 13
4.6 Object Composition .................................................................................................................................. 14
5. Object Model Design ...................................................................................................................................... 16
6. Resources....................................................................................................................................................... 17
7. References...................................................................................................................................................... 17
ii http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
1. Introduction
This document describes rules and recommendations for developing applications and class libraries using the
C# Language. The goal is to define guidelines to enforce consistent style and formatting and help developers
avoid common pitfalls and mistakes.
Specifically, this document covers Naming Conventions, Coding Style, Language Usage, and Object Model
Design.
1.1 Scope
This document only applies to the C# Language and the .NET Framework Common Type System(CTS) it
implements. Although the C# language is implemented alongside the .NET Framework, this document does not
address usage of .NET Framework class libraries. However, common patterns and problems related to C#’s
usage of the .NET Framework are addressed in a limited fashion.
Even though standards for curly-braces ( or ) and white space(tabs vs. spaces) are always controversial,
these topics are addressed here to ensure greater consistency and maintainability of source code.
Much like the ensuing coding standards, this document requires standards in order to ensure clarity when
stating the rules and guidelines. Certain conventions are used throughout this document to add emphasis.
Below are some of the common conventions used throughout this document.
Keywords:
Try Emphasizes that the rule should be attempted whenever possible and appropriate.
http://weblogs.asp.net/lhunt/ 1
Lance Hunt C# Coding Standards
Access Modifier
C# keywords , , , and declare the allowed code-
accessibility of types and their members. Although default access modifiers vary, classes and most
other members use the default of . Notable exceptions are interfaces and enums which
both default to public.
Camel Case
A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized.
Example:
Identifier
A developer defined token used to uniquely name a declared object or object instance.
Example:
Magic Number
Any numeric literal used within an expression (or to initialize a variable) that does not have an
obvious or well-known meaning. This usually excludes the integers 0 or 1 and any other numeric
equivalent precision that evaluates as zero.
Pascal Case
A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized.
Example:
Premature Generalization
As it applies to object model design; this is the act of creating abstractions within an object model
not based upon concrete requirements or a known future need for the abstraction. In simplest
terms: “Abstraction for the sake of Abstraction.”
2 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
This section contains tables describing a high-level summary of the major standards covered in this document.
These tables are not comprehensive, but give a quick glance at commonly referenced elements.
“c” = camelCase
“P” = PascalCase
“_” = Prefix with _Underscore
“x” = Not Applicable.
Code Style
Source Files One Namespace per file and one class per file.
Curly Braces On new line. Always use braces when optional.
Indention Use tabs with size of 4.
Comments Use or but not and do not flowerbox.
Variables One variable per declaration.
http://weblogs.asp.net/lhunt/ 3
Lance Hunt C# Coding Standards
Code Style
Native Data Types Use built-in C# native data types vs .NET CTS types.
(Use NOT !"#
Enums Avoid changing default type.
Generics Prefer Generic Types over standard or strong-typed classes.
Properties Never prefix with or $
Methods Use a maximum of 7 parameters.
base and this Use only in constructors or within an override.
Ternary conditions Avoid complex conditions.
foreach statements Do not modify enumerated items within a % statement.
Conditionals Avoid evaluating Boolean conditions against or .
No embedded assignment.
Avoid embedded method invocation.
Exception Handling Do not use exceptions for flow control.
Use % &' not % & ' when re-throwing.
Only catch what you can handle.
Use validation to avoid exceptions.
Events Always check for null before invoking.
Locking Use ()# vs. $* )#
Do not lock on an object type. Avoid locking on % $
Prefer locking on private objects.
Dispose() & Close() Always invoke them if offered.
Finalizers Avoid.
Use the C# Destructors.
Do not create + , )# method.
AssemblyVersion Increment manually.
ComVisibleAttribute Set to for all assemblies.
2. Naming Conventions
Consistency is the key to maintainable code. This statement is most true for naming your projects, source files,
and identifiers including Fields, Variables, Properties, Methods, Parameters, Classes, Interfaces, and
Namespaces.
4 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
- .
*
/ %
0 1
Example:
5 2 $7 $ 8 9: 5 2 $7 $ 9:
5 2 $7
Avoid including more than one ,* (global), or ; 1 (global) per file. Use a
descriptive file name when containing multiple ,* , or ; 1 .
Example:
$ <:
http://weblogs.asp.net/lhunt/ 5
Lance Hunt C# Coding Standards
Example:
5 2 $7
Examples:
, 3 > 3
> -
* 3 1 > * 3 1
3 1
Example:
& Example:
+ (? :
Generic Parameter
Type = %)? : 8#
? : = )#
Example:
*4 )#
1 3 / )3 1 #
6 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
Example:
1
Field (Private) Camel Case and prefix with a single underscore (@) character.
Example:
1 @ '
Example:
Example:
* 2 5 = 1 '
Example:
*4 ) 1 4 A #
http://weblogs.asp.net/lhunt/ 7
Lance Hunt C# Coding Standards
3. Coding Style
Coding style causes the most inconsistency and controversy between developers. Each developer has a
preference, and rarely are two the same. However, consistent layout, format, and organization are key to
creating maintainable code. The following sections describe the preferred way to implement C# source code in
order to create readable, clear, and consistent code that is easy to understand and maintain.
3.1 Formatting
- .
E3 BA 3 "A 3 !F
.
E3 BF
E3 "F
E3 !F
8 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
G;G> = ; 2
6 ;G *> 0 =H (
23 > 4
? 4 :
3 % & 1 ( % J 1 I 1>
? :?.E
?.E ;3 3E
? 1 :
? 1 :
? ( <I 1I <I / I :
? 1 :
? 1 :
FF:
FF:? :
? 4 :
4. Language Usage
4.1 General
Do not omit access modifiers. Explicitly declare all identifiers with the appropriate access modifier
instead of allowing the default.
Example:
http://weblogs.asp.net/lhunt/ 9
Lance Hunt C# Coding Standards
- .
/ 7 * ) 1 1 #
.
/ 7 * ) 1 1 #
E > / ) #F
E / ) #F
% NOT $ BK
NOT $ !"
1 NOT $ KC
1 NOT $ 1
Only declare member variables as . Use properties to provide access to them with
, , or access modifiers.
Avoid specifying a type for an - use default of unless you have an explicit need for 1.
Avoid using inline numeric literals (magic numbers). Instead, use a or * .
Avoid declaring inline string literals. Instead use Constants, Resources, Registry or other data
sources.
Only declare for simple types.
Declare variables for complex types.
Avoid direct casts. Instead, use the “ ” operator and check for .
Example:
8 G 8 < 5 ; )#'
; < G 8 ; '
) .< #
10 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
< B'
8 < ' 4 $
& < ) # ' *4 4 $
Floating point values should include at least one digit before the decimal place and one after.
Example: totalPercent < 0.05;
Try to use the “L” prefix for string literals instead of escaped strings.
Prefer 1$+ () or 1- over string concatenation.
Never concatenate strings inside a loop.
Do not compare strings to 1$* or JI to check for empty strings. Instead, compare by
using 1$5 1 % << M.
Avoid hidden string allocations within a loop. Use 1$ )# instead.
Example: (ToLower() creates a temp string)
- .
< 9B'
1 < J % I'
) 5 E F$ $ 5 & )# << #
< 5 E F$ ;'
.
< 9B'
1 < J % I'
% J 1 < I 1
9 & % & $
) 1$ ) 5 E F$ A A #<< M#
< 5 E F$ ;'
http://weblogs.asp.net/lhunt/ 11
Lance Hunt C# Coding Standards
- .
) / << #
.
) / #
- .
))) : @% 1% # QQ ) .< @% 1% ## QQ ) ?
@ 4 ##
.
2 1% < ) :< @% 1% #'
2 1% < ) << @% 1% #'
/ < ) ? @ 4/ #'
)) 2 1% QQ . 2 1%# QQ / #
- .
) / << #
'
.
(IsValid#
Only use & % statements for simple operations with parallel conditional logic.
Prefer nested over & % for short conditional sequences and complex
conditions.
Prefer polymorphism over & % to encapsulate and delegate complex operations.
12 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
If re-throwing an exception, omit the exception argument from the % & statement so the original
call stack is preserved.
Example:
- .
%)*4 4#
5 1) 4#'
% & 4'
.
%)*4 4#
5 1) 4#'
% &'
- .
$ )#'
%)*4 4#
% 4 .
.
) $ .< $ #
$ )#'
Avoid defining custom exception classes. Use existing exception classes instead.
When a custom exceptions is required;
Always derive from 3 *4 .
Always override the 1)# method and 1 G to provide
serialization.
Always implement the Exception Constructor Pattern:
*4 )#'
*4 ) 1 1 #'
*4 ) 1 1 A *4 *4 #'
http://weblogs.asp.net/lhunt/ 13
Lance Hunt C# Coding Standards
)- ( 1 #
)* $ ; ) )- ( 1 #A ##
Consider overriding *S )# on a .
Always override the *S G (<<) when overriding the *S )# method.
Always override the 1 G when overriding the 1)# method.
Always call )# or ; )# on classes that offer it.
Wrap instantiation of ; objects with a “ 1I statement to ensure that ; )# is
automatically called.
Example:
14 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
Always implement the ; interface & pattern on classes referencing external resources.
Example: (shown with optional Finalizer)
; )#
; ) #'
$ + , ) % #'
; ) 1#
) 1#
+ % ) 1 8 #$
+ & ) 1 8 #$
1 $
D , $ ) #
T- )#
; ) #$
; ) #'
http://weblogs.asp.net/lhunt/ 15
Lance Hunt C# Coding Standards
16 http://weblogs.asp.net/lhunt/
Lance Hunt C# Coding Standards
6. Resources
FxCop - a code analysis tool that checks .NET managed code assemblies for conformance to the Microsoft
.NET Framework Design Guidelines.
http://www.gotdotnet.com/team/fxcop/
7. References
“MSDN: .NET Framework Developer’s Guide: Common Type System”, Microsoft Corporation, 2004,
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconthecommontypesystem.asp
“MSDN: C# Language Specification v1.5”, Scott Wiltamuth & Anders Hejlsberg, Microsoft Corporation, 2003,
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_15.asp
“MSDN: Design Guidelines for Class Library Developers”, Microsoft Corporation, 2004,
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asp
“Applied Microsoft .NET Framework Programming”, Jeffrey Richter, January 23, 2002, 1st ed., Microsoft Press,
ISBN: 0735614229
http://weblogs.asp.net/lhunt/ 17