5. bbconcepteur@gmail.com goodluck guy!
Page 5
bbconcepteur@gmail.com goodluck guy!
1 INTRODUCTION
1.1 Overview
Superior coding techniques and programming practices are hallmarks of a professional programmer.
The bulk of programming consists of making many small choices, which collectively attempt to solve
a large set of problems. A programmer's skill and expertise largely determine the wisdom of those
choices. This document demonstrates how an organization’s C# coding conventions can be enforced
effectively.
1.2 Definitions, Acronyms and Abbreviations
This document provides rules, recommendations, examples for many of the topics discussed.
Rule is the guideline that developers have to follow (mandatory)
Recommendation is the guideline for reference only (optional)
The following typographic conventions are used in this guide:
Example of convention Description
[RULE] Rule
[REC] Recommendation
1.3 References
Document Title Original Copy
Capitalization Styles http://msdn.microsoft.com/library/default.asp?url=/library
/en-us/cpgenref/html/cpconcapitalizationstyles.asp
2 Environmental Setting
2.1 VS.NET Setting for Tabs
[RULE 2.10] Different applications/editors interpret tabs differently. VS.NET provides an option to
insert spaces in place of tabs. Enabling this option will avoid the issues with tabs across the
applications/editors. Use four spaces in places of each tab. Avoid using tabs anywhere in the source
code.
Follow the below step to change the VS.Net settings.
Tools>Option>Text Editor>C#>Tabs – Select Insert Spaces (VS.NET) File Organization
2.2 Source Files
[REC 2.10] File name should match with class name and should be meaningful. This convention
makes things much easier.
6. bbconcepteur@gmail.com goodluck guy!
Page 6
bbconcepteur@gmail.com goodluck guy!
[RULE 2.15] Each source file contains a single public class or interface.
[REC 2.15] When private classes and interfaces are associated with a public class, put them in the
same source file as the public class.
2.3 Source File Organization
[RULE 2.20] Source files have the following ordering:
Beginning comments. See comments and documentation section
Using directives
Namespace declaration
Class and interface declarations
3 Code Layout
3.1 Line Length
[RULE 3.10] Avoiding lines longer than 120 characters, including space characters for indentation
purpose.
3.2 Wrapping Lines
[RULE 3.15]
When an expression will not fit on a single line, break it according to the below principles:
Break after a comma or operator
Prefer higher-level breaks to lower-level breaks.
Align the new line at the next level of the previous line.
Example of breaking method calls:
LongMethodCall(expr1, expr2, expr3,
expr4, expr5);
Examples of breaking an arithmetic expression.
The first is preferred, since the break occurs outside of the parenthesized expression (higher level
rule).
var = a * b / (c - g + f) + _
4 * z; //---------PREFER
var = a * b / (c - g + _
f) + 4 * z; //---------AVOID
7. bbconcepteur@gmail.com goodluck guy!
Page 7
bbconcepteur@gmail.com goodluck guy!
3.3 Use #region to Group Members
[RULE 3.20] If a class contains a large number of members, attributes, and/or properties, preferably,
separate regions to split-up the private, protected, and internal members, methods , events and
properties . It is also allowed to use the #region construct for separating the smaller auxiliary classes
from the main class.
#region <Name of the region>
// Code goes here
#end region
3.4 One Statement per line
[RULE 3.25] Where appropriate, avoid placing more than one statement per line.
An exception is a loop, such as for (i = 0; i < 100; i++)
3.5 Indentation and Spacing
3.5.1 Statements Must Use Appropriate Indentation
[RULE 3.30] Check to ensure that all statements within methods are properly indented. Use four
white space characters to indent sub blocks of source code.
3.5.2 Blank line
[REC 3.10] Use one blank line to separate logical groups of code.
3.5.3 Curly Braces
[RULE 3.35]
Curly braces ({}) should be in the same level as the code outside the braces.
The curly braces should be on a separate line and not in the same line as if, for etc.
if ( ... )
{
// PREFER
}
if ( ... ) {
// AVOID
}
3.6 Method Definitions Must Not Exceed 200 Lines
[RULE 3.40] To aid readability of source code, individual method definitions must not exceed 200
source lines.
3.7 Inter-term Spacing
[RULE 3.45] There will be a single space after a comma or a semicolon, example:
8. bbconcepteur@gmail.com goodluck guy!
Page 8
bbconcepteur@gmail.com goodluck guy!
TestMethod(a, b, c); //--------CORRECT
TestMethod(a,b,c); //--------WRONG
TestMethod( a, b, c ); //--------WRONG
A single space will surround operators, example:
a = b; //--------CORRECT
a=b; //--------WRONG
3.8 Declaration Only Source Files Must Be Avoided
[RULE 3.50] Source files containing declarations only must be avoided. Constants, enums, type
definitions, declare statements and variables etc. are best grouped with the procedures to which they
relate, rather than as part of special "declaration only" source files
4 Comments
[REC 3.15] The purpose of adding comments to code is to provide a plain English description of what
your code is doing:
At a higher level of abstraction than the code is doing.
Talk "What" the code does, not "How" the code works. The comment which shows exactly
how the code works may change as it gets updated or revised.
[RULE 4.10] Use only English for comments.
4.1 Single Line Comments
[RULE 4.15]
Write inline comments wherever required
Use // for inline comments
4.2 File Header
[RULE 4.20]
Each file shall contain a header block. The header block must consist of the following
Copyright statement
Created By
Created Date
Description about the file and Revision History
Example:
//========================================================================
// Copyright <CLIENT NAME>
// All Rights Reserved
// Created by : <AUTHOR>
9. bbconcepteur@gmail.com goodluck guy!
Page 9
bbconcepteur@gmail.com goodluck guy!
// Create Date : <MM/DD/YYYY/>
// Description : <Description of the file>
//
// Revision History:
//
// Rev# Date By Description
// 1 <MM/DD/YYYY> <Author> <Summary>
//
//========================================================================
[REC 4.10] The page header can have a TODO: for pending tasks to indicate the pending activities of
the class/file.
4.3 Routine Header
[REC 4.15]
Use XML tags for documenting types and members.
All public and protected methods, class definition shall be documented using XML tags.
XML Tags comments for Types, Fields, Events and Delegates are optional.
Using these tags will allow IntelliSense to provide useful details while using the types. Also,
automatic documentation generation relies on these tags.
Standard Routine Header comment block includes the following section headings
Section Heading Comment Description Notes
<summary> What the sub/function does (not how) Mandatory
<remarks> List of each external condition such as variables,
control, or file that is not obvious
If any
<param> List all parameter(s) with brief explanation.
Parameters are on a separate line with inline
comments
If any
<returns> Explanation of the value returned by function Only use in function
<exception> Description of why the exception would be triggered.
Add caption=”” to the exception tag to name the
exception
If any
<example> Use this tag to introduce a code use example If any
<code> Use within the <example> tag to detail the example
code. Attributes include lang=”C#”, title=”” and
description=””
If any
<seealso> Link to another method, class, etc
<modified> Name of modifier and date performed on a separate
line.
If any
Notes:
10. bbconcepteur@gmail.com goodluck guy!
Page 10
bbconcepteur@gmail.com goodluck guy!
1. With the event function such as cmdOK_Click, Form_Load, the header comment
blocks can be unnecessary
2. Typing /// in VS.NET just above the method/function will automatically create XML
tags
Refer the below URL for more information about XML style documentation
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcorixmldocumentation.asp
4.4 Reminder Comments
[REC 4.20]
Make use of “TODO” for pending tasks.
Comments beginning 'TODO:” will be treated as reminder comments and should describe the issue
appropriately including the name of the developer responsible for the comment and the date the issue
was identified.
4.5 Block Comments
[REC 4.25] Consider adding comments to in front of major blocks of code, but avoid commenting to
every (or almost every) lines of code.
4.6 Fixing Error Comments
[RULE 4.25] Do not embed any kind of comments about fixing error in the middle code source code.
Instead, for only major error fixes, put those comments to the header comment in the revision history
section.
4.7 Spelling and Grammar
[REC 4.30] Do a spell check on comments and also make sure proper grammar and punctuation is
used.
5 Declarations and Initializations
5.1 Number of Declarations Per Line
[RULE 5.10] One declaration per line since it encourages commenting.
int a, b; //------ AVOID
int a; //------PREFER
int b;
5.2 Declaration Precedence
[REC 5.10]
The following order is preferred:
Constants
Public
11. bbconcepteur@gmail.com goodluck guy!
Page 11
bbconcepteur@gmail.com goodluck guy!
Protected
Private
Note: All Public constant declarations must appear before private constant declarations within the
declarations section of a source file.
5.3 Initialization
[REC 5.15] Try to initialize local variables where they are declared.
Example:
double width = 1000;
string firstName = ”Doe”;
6 Naming Convention
6.1 Capitalization Styles
This section explains capitalizations will be used
6.1.1 Pascal Casing
This convention capitalizes the first character of each word (as in TestCounter).
Note: Two-letter abbreviations in Pascal casing have both letters capitalized (Ex: UIEntry)
6.1.2 Camel Casing
This convention capitalizes the first character of each word except the first one. E.g. testCounter.
6.1.3 Upper Case
This convention capitalizes all character of the word. Ex: PI
6.2 Capitalization Summary
[RULE 6.10] Use the following table for naming conventions.
Type Case Hungarian Example Notes
Class Pascal No AppDomain Class names must be nouns
or noun phrase.
Don’t use C prefix (to indicate
‘class’) for class name
Const Field UPPER No PI
Enum Type Pascal No
ErrorLevel (normal)
SearchOptions
(bitwise)
Use singular names for
enumeration types
Do not add Enum to the end
of Enum name
If the Enum represents
bitwise flags, end the name
with a plural
12. bbconcepteur@gmail.com goodluck guy!
Page 12
bbconcepteur@gmail.com goodluck guy!
Event Pascal No ValueChange Name event handlers with the
EventHandler suffix
Use two parameters named
sender and e
Exception class Pascal No SystemException Suffix with Exception
Parameter and
Procedure-
Level Variables
Camel Yes recordNumber
Class-Level
Variables
Camel Yes firstName
GUI Objects Camel Yes btnCancel
txtName
Post fix with type name
without abbreviations
Interface Pascal Yes IDisposable
IEnumerable
IComponent
Prefix with I
Name interfaces with nouns
or noun phrases or adjectives
describing behavior.
Method Pascal No ToString Name methods with verbs or
verb phrases.
Namespace Pascal No System.Drawing
Property Pascal No BackColor Name properties using nouns
or noun phrases
6.3 Object Naming Conventions for Standard Objects
[RULE 6.15] This section could be customized depended on the project.
Object Prefix Example
Button btn btnCustomer
CheckBox chk chkCustomer
CheckBoxList chkl chkLCustomer
ColorDialog cdg cdgBox
ComboBox cbo cboCustomer
ContextMenu cmu cmuCustomer
CrystalReportViewer crv crvCustomer
DataGrid dgd dgdCustomer
DateTimePicker dtp dtpReportGenerated
DomainUpDow dud dudDomain
ErrorProvider epr eprCustomer
FontDialog fdg fdgCustomer
Form frm frmCustomer
GridControl grd grdCustomer
GroupBox grp grpCustomer
HelpProvider hlp hlpCustomer
HScrollBar hsb hsbCustomer
14. bbconcepteur@gmail.com goodluck guy!
Page 14
bbconcepteur@gmail.com goodluck guy!
DataSet ds
DataView dv
DataRow dr
DataRowView drv
DataColumn dc
DataTable dt
Transaction trn
Parameters prm
Crystal ReportDocument crrpd
Crystal Tables crtbs
Crystal Table crtbl
Crystal TableLogOnInfo crtli
Crystal ConnectionInfo crcnn
Crystal Sections crscs
Crystal Section crsc
Crystal ReportObjects crros
Crystal ReportObject crro
Crystal SubreportObject rsro
SqlDataReader drd
OleDbDataReader drd
6.5 Menu Naming Conventions
[RULE 6.25] Applications frequently use an abundance of menu controls. As a result, you need a
different set of naming conventions for these controls. Menu control prefixes should be extended
beyond the initial menu label by adding an additional prefix for each level of nesting, with the final
menu caption at the end of the name string. For example:
Menu Caption Sequence Menu Handler Name
Help.Contents mnuHelpContents
File.Open mnuFileOpen
Format.Character mnuFormatCharacter
File.Send.Fax mnuFileSendFax
File.Send.Email mnuFileSendEmail
When this convention is used, all members of a particular menu group are listed next to each other in
the object drop-down list boxes. In addition, the menu control names clearly document the menu
items to which they are attached.
6.6 Third-party Controls
[REC 6.10] Each third-party control used in an application should be listed in the application's
overview comment section, providing the prefix used for the control, the full name of the control, and
the name of the software vendor:
15. bbconcepteur@gmail.com goodluck guy!
Page 15
bbconcepteur@gmail.com goodluck guy!
Prefix Control Type Vendor
cmdm Command Button MicroHelp
7 Programming Practices
7.1 Writing Methods
1. Method name should tell what it does - Do not use misleading names. If the method name
is obvious, there is no need of documentation explaining what the method does.
2. A method should do only 'one job'. Do not combine more than one job in a single method,
even if those jobs are very small.
3. Avoid providing functions with many arguments. Use struct to wrap arguments
7.2 Using Statements
1. A switch statement must always contain a default branch which handles unexpected
cases.
2. Single Line if Statement Must Not Be Used - In the interest of making source code more
readable, single line if statements are to be avoided.
3. if Statements Must Not Be Nested More Than 3 Levels - To ensure that procedures are
easy to understand, test and maintain, if statements must not be nested beyond three levels
deep.
7.3 Miscellaneous Practices
1. Floating point values shall not be compared using either the == or! = operators - Most
floating point values have no exact binary representation and have a limited precision.
Exception: When a floating point variable is explicitly initialized with a value such as 1.0 or
0.0, and then checked for a change at a later stage.
2. Do not use ‘magic’ numbers – Don’t use magic numbers, i.e. place constant numerical
values directly into the source code. Exceptions: Values 0, 1 and null can be used safely.
Magic number is any numeric literal used in your program other than the numbers 0 and 1,
and a string literal is any quoted string.
3. Minimize the Number of Loops Inside a try Block - Minimize the number of loops inside a
try block, and minimize the number of try blocks inside a loop. A long loop could amplify the
overhead of structured exception handling.
4. Self Check - In the application start up, do some kind of "self check" and ensure all required
files and dependencies are available in the expected locations. Check for database
16. bbconcepteur@gmail.com goodluck guy!
Page 16
bbconcepteur@gmail.com goodluck guy!
connection in start up, if required. Give a friendly message to the user in case of any
problems.
5. Default Config Settings - If the required configuration file is not found, application should be
able to create one with default values. If a wrong value found in the configuration file,
application should throw an error or give a message and also should tell the user what are
the correct values.
6. Use validation code to reduce unnecessary exceptions - If we know that specific
avoidable condition can happen, proactively write code to avoid it. For eg, adding validation
checks such as checking for null before using and item from the cache can significantly
increase performance by avoiding exceptions.
7. Use finally Block to Ensure that Resources are Released.
8. Suppress Finalization in the Dispose Method - If the calling code calls Dispose, we do not
want the garbage collector to call a finalizer because the unmanaged resources will already
been returned to the operating system. We must prevent the garbage collector from calling
the finalizer using GC.SuppressFinalization in our Dispose method.
9. Do not modify or re-organize current source code - Unless required by fixing errors or
reformatting source code to follow this coding convention. Try to keep modifying the current
source as least as possible. This makes comparing different version of source code easier.
10. Be consistent through out the code - For anything that is not enforced by this coding
convention document, developers can use any convention they feel convenient. But no
matter what convention chosen, that should be applied consistently through out the code.