SlideShare a Scribd company logo
bbconcepteur@gmail.com goodluck guy!
Page 1
C# CODING CONVENTIONS
Date: 10/17/2015
Version: 1.0
Status: Baseline
bbconcepteur@gmail.com goodluck guy!
Page 2
bbconcepteur@gmail.com goodluck guy!
Revision History
Date Version Description Author
06/17/2005 1.0 Initial Draft Hung Ho
bbconcepteur@gmail.com goodluck guy!
Page 3
bbconcepteur@gmail.com goodluck guy!
Table of Contents
1 INTRODUCTION ............................................................................................................................ 5
1.1 OVERVIEW................................................................................................................................. 5
1.2 DEFINITIONS, ACRONYMS AND ABBREVIATIONS ........................................................................... 5
1.3 REFERENCES............................................................................................................................. 5
2 ENVIRONMENTAL SETTING........................................................................................................ 5
2.1 VS.NET SETTING FOR TABS ...................................................................................................... 5
2.2 SOURCE FILES........................................................................................................................... 5
2.3 SOURCE FILE ORGANIZATION ..................................................................................................... 6
3 CODE LAYOUT.............................................................................................................................. 6
3.1 LINE LENGTH ............................................................................................................................. 6
3.2 WRAPPING LINES....................................................................................................................... 6
3.3 USE #REGION TO GROUP MEMBERS ........................................................................................... 7
3.4 ONE STATEMENT PER LINE ......................................................................................................... 7
3.5 INDENTATION AND SPACING........................................................................................................ 7
3.5.1 Statements Must Use Appropriate Indentation ................................................................ 7
3.5.2 Blank line.......................................................................................................................... 7
3.5.3 Curly Braces..................................................................................................................... 7
3.6 METHOD DEFINITIONS MUST NOT EXCEED 200 LINES ................................................................. 7
3.7 INTER-TERM SPACING ................................................................................................................ 7
3.8 DECLARATION ONLY SOURCE FILES MUST BE AVOIDED .............................................................. 8
4 COMMENTS................................................................................................................................... 8
4.1 SINGLE LINE COMMENTS............................................................................................................ 8
4.2 FILE HEADER............................................................................................................................. 8
4.3 ROUTINE HEADER...................................................................................................................... 9
4.4 REMINDER COMMENTS............................................................................................................. 10
4.5 BLOCK COMMENTS .................................................................................................................. 10
4.6 FIXING ERROR COMMENTS....................................................................................................... 10
4.7 SPELLING AND GRAMMAR......................................................................................................... 10
5 DECLARATIONS AND INITIALIZATIONS.................................................................................. 10
5.1 NUMBER OF DECLARATIONS PER LINE ...................................................................................... 10
5.2 DECLARATION PRECEDENCE .................................................................................................... 10
5.3 INITIALIZATION ......................................................................................................................... 11
6 NAMING CONVENTION .............................................................................................................. 11
6.1 CAPITALIZATION STYLES........................................................................................................... 11
6.1.1 Pascal Casing................................................................................................................. 11
6.1.2 Camel Casing................................................................................................................. 11
6.1.3 Upper Case .................................................................................................................... 11
6.2 CAPITALIZATION SUMMARY....................................................................................................... 11
bbconcepteur@gmail.com goodluck guy!
Page 4
bbconcepteur@gmail.com goodluck guy!
6.3 OBJECT NAMING CONVENTIONS FOR STANDARD OBJECTS......................................................... 12
6.4 OBJECT NAMING CONVENTION FOR DATABASE OBJECTS........................................................... 13
6.5 MENU NAMING CONVENTIONS .................................................................................................. 14
6.6 THIRD-PARTY CONTROLS ......................................................................................................... 14
7 PROGRAMMING PRACTICES.................................................................................................... 15
7.1 WRITING METHODS.................................................................................................................. 15
7.2 USING STATEMENTS ................................................................................................................ 15
7.3 MISCELLANEOUS PRACTICES.................................................................................................... 15
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.
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
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:
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>
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:
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
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
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
bbconcepteur@gmail.com goodluck guy!
Page 13
bbconcepteur@gmail.com goodluck guy!
ImageList iml imlCustomer
Label lbl lblCustomer
LinkLabel llbl llblCustomer
ListBox lst lstCustomer
ListView lvw lvwCustomer
Mainmenu mnu mnuCustomer
MonthCalendar cal calMonthly
NotifyIcon nic nicCustomer
NumericUpDown nud nudCustomer
OpenFileDialog dlg dlgCustomer
PageSetUpDialogue psd psdCustomer
Panel pnl PnlCustomer
PictureBox pic picCustomer
PrintDialogue pdg pdgCustomer
PrintDocument pdc pdcCustomer
PrintPreviewControl ppc ppcCustomer
PrintPreviewDialogue ppd ppdCustomer
ProgressBar prg prgCustomer
RadioButton rad radCustomer
RichTextBox rtb rtbCustomer
SaveFileDialogue sfd sfdCustomer
Splitter spl splCustomer
Statusbar sts stsCustomer
TabControl tab tabCustomer
TextBox txt txtCustomer
Timer tmr tmrCustomer
Toolbar tbr tbrCustomre
ToolTip tip tipCustomer
Trackbar trk trkCustomer
TreeView tvw tvwCustomer
VSScrollBar vsb vsbCustomer
6.4 Object Naming Convention for Database Objects
[RULE 6.20] This section could be customized depended on the project.
Name Prefix
SqlConnection con
SqlCommand cmd
SqlParameter prm
ParameterDirection prmd
SqlDataAdapter adp
OleDbConnection cnn
OleDbCommand cmd
OleDbDataAdapter adp
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:
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
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.
Ad

Recommended

R Exts
R Exts
Ajay Ohri
 
What's New in ZW3D 2012 v1.0
What's New in ZW3D 2012 v1.0
VX
 
3 kc18039acaatqzza v1_alcatel-lucent 1646 synchronous multiplexer compact rel...
3 kc18039acaatqzza v1_alcatel-lucent 1646 synchronous multiplexer compact rel...
jchung6133
 
R Data
R Data
Ajay Ohri
 
Chapter1 6
Chapter1 6
alish sha
 
BOOK - IBM DB2 9 FOR zOS
BOOK - IBM DB2 9 FOR zOS
Satya Harish
 
Assembly
Assembly
nick333y
 
Java code conventions
Java code conventions
Armando Daniel
 
1660 S M Oper R4
1660 S M Oper R4
Fxx
 
BOOK - IBM Security on ibm z vse
BOOK - IBM Security on ibm z vse
Satya Harish
 
Code Conventions
Code Conventions
51 lecture
 
Spring Reference
Spring Reference
Syed Shahul
 
R Ints
R Ints
Ajay Ohri
 
Spring Reference
Spring Reference
asas
 
MXIE Phone User's Manual
MXIE Phone User's Manual
Matthew Rathbun
 
Guam: Stormwater Management Manual
Guam: Stormwater Management Manual
Sotirakou964
 
Latex2e
Latex2e
Inam ullah Johar
 
Igo Primo Navigation Software User Manual
Igo Primo Navigation Software User Manual
WilliamS78
 
Ref
Ref
guestc39ded
 
WebHost Manager 1.01 User Guide
WebHost Manager 1.01 User Guide
webhostingguy
 
First7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programming
xmeszeus
 
Arm assembly language by Bournemouth Unversity
Arm assembly language by Bournemouth Unversity
Stephan Cadene
 
301132
301132
Hiroshi Ono
 
Vhdl cookbook
Vhdl cookbook
Thọ Nguyễn
 
Gdfs sg246374
Gdfs sg246374
Accenture
 
Code Conventions
Code Conventions
provadaordem
 
Implementing tws extended agent for tivoli storage manager sg246030
Implementing tws extended agent for tivoli storage manager sg246030
Banking at Ho Chi Minh city
 
CodeConventions.pdf
CodeConventions.pdf
Jeff Smith
 
Final report
Final report
Sheikh Toriqul Islam
 
Learn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 Features
ZEZUA Z.
 

More Related Content

What's hot (14)

1660 S M Oper R4
1660 S M Oper R4
Fxx
 
BOOK - IBM Security on ibm z vse
BOOK - IBM Security on ibm z vse
Satya Harish
 
Code Conventions
Code Conventions
51 lecture
 
Spring Reference
Spring Reference
Syed Shahul
 
R Ints
R Ints
Ajay Ohri
 
Spring Reference
Spring Reference
asas
 
MXIE Phone User's Manual
MXIE Phone User's Manual
Matthew Rathbun
 
Guam: Stormwater Management Manual
Guam: Stormwater Management Manual
Sotirakou964
 
Latex2e
Latex2e
Inam ullah Johar
 
Igo Primo Navigation Software User Manual
Igo Primo Navigation Software User Manual
WilliamS78
 
Ref
Ref
guestc39ded
 
WebHost Manager 1.01 User Guide
WebHost Manager 1.01 User Guide
webhostingguy
 
First7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programming
xmeszeus
 
Arm assembly language by Bournemouth Unversity
Arm assembly language by Bournemouth Unversity
Stephan Cadene
 
1660 S M Oper R4
1660 S M Oper R4
Fxx
 
BOOK - IBM Security on ibm z vse
BOOK - IBM Security on ibm z vse
Satya Harish
 
Code Conventions
Code Conventions
51 lecture
 
Spring Reference
Spring Reference
Syed Shahul
 
Spring Reference
Spring Reference
asas
 
MXIE Phone User's Manual
MXIE Phone User's Manual
Matthew Rathbun
 
Guam: Stormwater Management Manual
Guam: Stormwater Management Manual
Sotirakou964
 
Igo Primo Navigation Software User Manual
Igo Primo Navigation Software User Manual
WilliamS78
 
WebHost Manager 1.01 User Guide
WebHost Manager 1.01 User Guide
webhostingguy
 
First7124911 visual-cpp-and-mfc-programming
First7124911 visual-cpp-and-mfc-programming
xmeszeus
 
Arm assembly language by Bournemouth Unversity
Arm assembly language by Bournemouth Unversity
Stephan Cadene
 

Similar to A sample c_sharp_coding_conventions (20)

301132
301132
Hiroshi Ono
 
Vhdl cookbook
Vhdl cookbook
Thọ Nguyễn
 
Gdfs sg246374
Gdfs sg246374
Accenture
 
Code Conventions
Code Conventions
provadaordem
 
Implementing tws extended agent for tivoli storage manager sg246030
Implementing tws extended agent for tivoli storage manager sg246030
Banking at Ho Chi Minh city
 
CodeConventions.pdf
CodeConventions.pdf
Jeff Smith
 
Final report
Final report
Sheikh Toriqul Islam
 
Learn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 Features
ZEZUA Z.
 
The MySQL Cluster API Developer Guide
The MySQL Cluster API Developer Guide
webhostingguy
 
Home automation
Home automation
Syed Muhammad Hammad-ud-Din
 
AdvFS Snapshots (kernel)
AdvFS Snapshots (kernel)
Justin Goldberg
 
Spring Framework Upgrade
Spring Framework Upgrade
v_mahesh76
 
Report on dotnetnuke
Report on dotnetnuke
Rishabh Gandhi
 
Good polb qms -jul24,2013
Good polb qms -jul24,2013
soenarto soendjaja
 
Expert_Programming_manual.pdf
Expert_Programming_manual.pdf
EMERSON EDUARDO RODRIGUES
 
Codeconventions 150003
Codeconventions 150003
Tomasz Waszczyk
 
Drools expert-docs
Drools expert-docs
Erick Ulisses Monfil Contreras
 
BOOK - IBM zOS V1R10 communications server TCP / IP implementation volume 1 b...
BOOK - IBM zOS V1R10 communications server TCP / IP implementation volume 1 b...
Satya Harish
 
html-css-bootstrap-javascript-and-jquery
html-css-bootstrap-javascript-and-jquery
MD. NURUL ISLAM
 
Git extensionsusermanual v09
Git extensionsusermanual v09
Zhanna Kazakova
 
Gdfs sg246374
Gdfs sg246374
Accenture
 
Implementing tws extended agent for tivoli storage manager sg246030
Implementing tws extended agent for tivoli storage manager sg246030
Banking at Ho Chi Minh city
 
CodeConventions.pdf
CodeConventions.pdf
Jeff Smith
 
Learn C# Includes The C# 3.0 Features
Learn C# Includes The C# 3.0 Features
ZEZUA Z.
 
The MySQL Cluster API Developer Guide
The MySQL Cluster API Developer Guide
webhostingguy
 
AdvFS Snapshots (kernel)
AdvFS Snapshots (kernel)
Justin Goldberg
 
Spring Framework Upgrade
Spring Framework Upgrade
v_mahesh76
 
BOOK - IBM zOS V1R10 communications server TCP / IP implementation volume 1 b...
BOOK - IBM zOS V1R10 communications server TCP / IP implementation volume 1 b...
Satya Harish
 
html-css-bootstrap-javascript-and-jquery
html-css-bootstrap-javascript-and-jquery
MD. NURUL ISLAM
 
Git extensionsusermanual v09
Git extensionsusermanual v09
Zhanna Kazakova
 
Ad

Recently uploaded (20)

Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
declaration of Variables and constants.pptx
declaration of Variables and constants.pptx
meemee7378
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
Ad

A sample c_sharp_coding_conventions

  • 1. [email protected] goodluck guy! Page 1 C# CODING CONVENTIONS Date: 10/17/2015 Version: 1.0 Status: Baseline
  • 2. [email protected] goodluck guy! Page 2 [email protected] goodluck guy! Revision History Date Version Description Author 06/17/2005 1.0 Initial Draft Hung Ho
  • 3. [email protected] goodluck guy! Page 3 [email protected] goodluck guy! Table of Contents 1 INTRODUCTION ............................................................................................................................ 5 1.1 OVERVIEW................................................................................................................................. 5 1.2 DEFINITIONS, ACRONYMS AND ABBREVIATIONS ........................................................................... 5 1.3 REFERENCES............................................................................................................................. 5 2 ENVIRONMENTAL SETTING........................................................................................................ 5 2.1 VS.NET SETTING FOR TABS ...................................................................................................... 5 2.2 SOURCE FILES........................................................................................................................... 5 2.3 SOURCE FILE ORGANIZATION ..................................................................................................... 6 3 CODE LAYOUT.............................................................................................................................. 6 3.1 LINE LENGTH ............................................................................................................................. 6 3.2 WRAPPING LINES....................................................................................................................... 6 3.3 USE #REGION TO GROUP MEMBERS ........................................................................................... 7 3.4 ONE STATEMENT PER LINE ......................................................................................................... 7 3.5 INDENTATION AND SPACING........................................................................................................ 7 3.5.1 Statements Must Use Appropriate Indentation ................................................................ 7 3.5.2 Blank line.......................................................................................................................... 7 3.5.3 Curly Braces..................................................................................................................... 7 3.6 METHOD DEFINITIONS MUST NOT EXCEED 200 LINES ................................................................. 7 3.7 INTER-TERM SPACING ................................................................................................................ 7 3.8 DECLARATION ONLY SOURCE FILES MUST BE AVOIDED .............................................................. 8 4 COMMENTS................................................................................................................................... 8 4.1 SINGLE LINE COMMENTS............................................................................................................ 8 4.2 FILE HEADER............................................................................................................................. 8 4.3 ROUTINE HEADER...................................................................................................................... 9 4.4 REMINDER COMMENTS............................................................................................................. 10 4.5 BLOCK COMMENTS .................................................................................................................. 10 4.6 FIXING ERROR COMMENTS....................................................................................................... 10 4.7 SPELLING AND GRAMMAR......................................................................................................... 10 5 DECLARATIONS AND INITIALIZATIONS.................................................................................. 10 5.1 NUMBER OF DECLARATIONS PER LINE ...................................................................................... 10 5.2 DECLARATION PRECEDENCE .................................................................................................... 10 5.3 INITIALIZATION ......................................................................................................................... 11 6 NAMING CONVENTION .............................................................................................................. 11 6.1 CAPITALIZATION STYLES........................................................................................................... 11 6.1.1 Pascal Casing................................................................................................................. 11 6.1.2 Camel Casing................................................................................................................. 11 6.1.3 Upper Case .................................................................................................................... 11 6.2 CAPITALIZATION SUMMARY....................................................................................................... 11
  • 4. [email protected] goodluck guy! Page 4 [email protected] goodluck guy! 6.3 OBJECT NAMING CONVENTIONS FOR STANDARD OBJECTS......................................................... 12 6.4 OBJECT NAMING CONVENTION FOR DATABASE OBJECTS........................................................... 13 6.5 MENU NAMING CONVENTIONS .................................................................................................. 14 6.6 THIRD-PARTY CONTROLS ......................................................................................................... 14 7 PROGRAMMING PRACTICES.................................................................................................... 15 7.1 WRITING METHODS.................................................................................................................. 15 7.2 USING STATEMENTS ................................................................................................................ 15 7.3 MISCELLANEOUS PRACTICES.................................................................................................... 15
  • 5. [email protected] goodluck guy! Page 5 [email protected] 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. [email protected] goodluck guy! Page 6 [email protected] 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. [email protected] goodluck guy! Page 7 [email protected] 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. [email protected] goodluck guy! Page 8 [email protected] 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. [email protected] goodluck guy! Page 9 [email protected] 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. [email protected] goodluck guy! Page 10 [email protected] 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. [email protected] goodluck guy! Page 11 [email protected] 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. [email protected] goodluck guy! Page 12 [email protected] 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
  • 13. [email protected] goodluck guy! Page 13 [email protected] goodluck guy! ImageList iml imlCustomer Label lbl lblCustomer LinkLabel llbl llblCustomer ListBox lst lstCustomer ListView lvw lvwCustomer Mainmenu mnu mnuCustomer MonthCalendar cal calMonthly NotifyIcon nic nicCustomer NumericUpDown nud nudCustomer OpenFileDialog dlg dlgCustomer PageSetUpDialogue psd psdCustomer Panel pnl PnlCustomer PictureBox pic picCustomer PrintDialogue pdg pdgCustomer PrintDocument pdc pdcCustomer PrintPreviewControl ppc ppcCustomer PrintPreviewDialogue ppd ppdCustomer ProgressBar prg prgCustomer RadioButton rad radCustomer RichTextBox rtb rtbCustomer SaveFileDialogue sfd sfdCustomer Splitter spl splCustomer Statusbar sts stsCustomer TabControl tab tabCustomer TextBox txt txtCustomer Timer tmr tmrCustomer Toolbar tbr tbrCustomre ToolTip tip tipCustomer Trackbar trk trkCustomer TreeView tvw tvwCustomer VSScrollBar vsb vsbCustomer 6.4 Object Naming Convention for Database Objects [RULE 6.20] This section could be customized depended on the project. Name Prefix SqlConnection con SqlCommand cmd SqlParameter prm ParameterDirection prmd SqlDataAdapter adp OleDbConnection cnn OleDbCommand cmd OleDbDataAdapter adp
  • 14. [email protected] goodluck guy! Page 14 [email protected] 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. [email protected] goodluck guy! Page 15 [email protected] 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. [email protected] goodluck guy! Page 16 [email protected] 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.