Anda di halaman 1dari 11

DotNetDaily.

net

Coding Standards for C#

This document was downloaded from http://www.dotnetdaily.net/ You are permitted to use and
distribute this document for any noncommercial purpose as long as you retain this license & copyrights
information. This document is provided on As-Is basis. The author of this document will not be
responsible for any kind of loss for you due to any inaccurate information provided in this document.

Coding Standards for C#

Contents
1.

2.

3.

Naming Conventions ....................................................................................................................... 2


1.1

General Rules........................................................................................................................... 2

1.2

Naming Conventions for ASP.NET Controls............................................................................. 3

Indentation, Spacing and Coding Style ............................................................................................ 5


2.1

General Rules........................................................................................................................... 5

2.2

Grouping Code......................................................................................................................... 6

Language Usage ............................................................................................................................... 7


3.1

4.

Code Commenting ........................................................................................................................... 9


4.1

5.

General Rules........................................................................................................................... 7

General Rules........................................................................................................................... 9

Exception Handling ........................................................................................................................ 10


5.1

General Rules......................................................................................................................... 10

http://dotnetdaily.net

Coding Standards for C#

C# Coding Standards for .NET


1. Naming Conventions
Terminology and Definitions:
Camel Case (camelCase): The first letter of the word is lower case and then each first letter
of the part of the word is upper case;
Pascal Case (PascalCase): The first letter of the word is upper case and then each first letter
of the part of the word is upper case;
Underscode Prefix (_underscore): The word begins with underscore char and for the rest of
the word use camelCase rule;

1.1 General Rules


1.1.1 Use Pascal Case for Class names:
Ex: public class HelloWorld { ... };
1.1.2 Use Pascal Case for Method names:
Ex: public void SayHello(string name) { ... };
1.1.3 Use Camel Case for variables and method parameters:
Ex:
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
1.1.4 Avoid all upper case or all lower case names;
1.1.5 Do not use Hungarian notation:
Example of Hungarian Notation:
string m_sName; (the prefix m_ means that is a member variable and s means that is
a string data type);

http://dotnetdaily.net

Coding Standards for C#

1.1.6 Avoid abbreviations longer than 5 characters;


1.1.7 Avoid using abbreviations unless the full name is excessive:
Ex:
Good: string address;

Not good: string addr;

1.1.8 Use meaningfull, descriptive words for naming variables;


1.1.9 Try to prefix Boolean variables with Can, Is or Has;
1.1.10 Do not use Underscore Prefix for local variables names;
1.1.11 All member variables must use Underscore Prefix so that they can be
identified from other local variables names;
1.1.12 Avoid naming conflicts with existing .NET Framework namespaces or types;
1.1.13 Do not include the parent class name within a property name:
Ex: Good: Customer.Name;

Not good: Customer.CustomerName;

1.1.14 When defining a root namespace, use a Product, a Company or a Developer


name as the root:
Ex: NorthwindApplication.Utilities;
1.1.15 Use Pascal Case for file names;
1.1.16 Method name should tell you what it does;
1.1.17 A method should do only one job. Do not combine multiple jobs in one
method even if those jobs have very few lines of code.
Ex:
protected void SaveCustomerName(string customerName)
{
//code here...
}

1.2 Naming Conventions for ASP.NET Controls


In general, naming ASP.NET controls is made using Camel Case naming convention, where
the prefix of the name is the abbreviation of the control type name.

http://dotnetdaily.net

Coding Standards for C#

Abbreviation ASP.NET Control


STANDARD CONTROLS
Button
btn
CheckBox
cb
CheckBoxList
cbl
DropDownList
ddl
FileUpload
fu
HiddenField
hdn
Hyperlink
lnk
Image
img
ImageButton
ibtn(btn)
Label
lbl
LinkButton
lbtn(btn)
ListBox
lb
Literal
lit
MultiView
mv
Panel
pnl
PlaceHolder
ph
RadioButton
rb
RadioButtonList
rbl
Table
tbl
TextBox
txt
View
v
DATA CONTROLS
DataList
dtl
DataPager
dp
DetailsView
dtv
EntityDataSource
ets
FormView
fv
GridView
gv
LinqDataSource
lds
ListView
lv
ObjectDataSource
ods
QueryExtender
qe
Repeater
rpt
SiteMapDataSource
smd
SqlDataSource
sds
XmlDataSource
xds
VALIDATION CONTROLS
CompareValidator
cpv
CustomValidator
ctv
RangeValidator
rv
RegularExpressionValidator
rev
RequiredFieldValidator
rfv
ValidationSummary
vs

http://dotnetdaily.net

Coding Standards for C#

2. Indentation, Spacing and Coding Style


Each programmer has a unique way of coding. While this fact is not a problem when you
do it for yourself, working in an organization and code in your own way may represent a big
problem for your team mates.
So its very important to follow some indentation and coding style rules for keeping the
code clean and readable for all programmers from the project.

2.1 General Rules


2.1.1
2.1.2
2.1.3
2.1.4

Use TAB for indentation. Do not use spaces. Recommended TAB size is 4;
Never declare more than one namespace per file;
Avoid putting multiple classes in a single file;
Comments should be in the same level as the code:
Ex:

// Format a message and display


string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;

2.1.5 Always use curly braces ({ and }) in a new line and in conditional
statements:
Ex:
protected void Page_Load(object sender, EventArgs e)
{
bool IsTrue;
if (IsTrue == true)
{
// Do something;
//....
return false;
}
}

2.1.6 Use one blank line to separate logical groups of code:


Ex:
public void SayHello(string name)
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTim
e.ToShortTimeString();

http://dotnetdaily.net

Coding Standards for C#

MessageBox.Show(message);
}

2.2 Grouping Code


2.2.1 Group internal class implementation by type in the following order:
1) Member variables;
2) Constructors and finalizers;
3) Nested Enums, Structs and Classes;
4) Properties;
5) Methods;
2.2.2 Sequence declarations within type groups based upon access modifier and
visibility:
1) Public;
2) Protected;
3) Internal;
4) Private;
2.2.3 Use regions (#region) to group related pieces of code together:
Ex:
namespace SampleApplication
{
public partial class _Default : System.Web.UI.Page
{
#region Private Members
// code here
#endregion
#region Constructors
// code here
#endregion
#region Public Properties
// code here
#endregion
#region Private Properties
// code here
#endregion
#region Public Methods
// code here
#endregion
#region Private Methods
// code here
#endregion

http://dotnetdaily.net

Coding Standards for C#

2.2.4 Do not hardcode numbers and strings. Use constant variables or resource
files;
2.2.5 Declare readonly or static readonly variables instead of constants for
complex types;
2.2.6 Avoid having very large files. If a file has more than 1000 lines of code
then its a good candidate for refactoring. Split it logically in two or more
classes;

3. Language Usage
In .NET, if you dont respect some basic rules about language usage you can end up by
spending a lot of time on debugging code and trace bugs caused by inadvertently written
code.

3.1 General Rules


3.1.1 Do not omit access modifiers. Explicitly declare all identifiers with the
appropriate access modifier instead of allowing them by default:
Ex:
Good:
protected void SaveCustomerName(string customerName)
{
//...
}

Bad:
void SaveCustomerName(string customerName)
{
//...
}

3.1.2 Only declare member variables as private. Use properties to provide


access to them with public, protected or internal access modifiers;
3.1.3 Convert strings to lower case or upper case before comparing. This will
ensure the string will match even if the string compared has a different case:
Ex:
if (name.ToLower() == "john")

http://dotnetdaily.net

Coding Standards for C#

{
// do something...
}

3.1.4 Use String.Empty instead of :


Ex:
Good:
if (name == String.Empty)
{
// do something...
}

Bad:
if (name == "")
{
// do something...
}

3.1.5 Try to use int for any non-fractional numeric values that will fit into int
data type, even for negative numeric values;
3.1.6 Only use long for variables potentially containing values too large for
int data type;
3.1.7 Use double for fractional numbers to insure decimal precisions in
calcultations;
3.1.8 Use float for fractional number that will not fit in decimal or double.
Still avoid using float unless you fully understand the implications
upon any calculations;
3.1.9 Use String.Builder instead of string when you have to manipulate
string objects in a loop;
3.1.10 Try to use @ prefix for string literals instead of escaped strings;
3.1.11 Avoid using ternary conditional operator. For complex operations can
be difficult to understand:
Ex:
int result = isValid ? 9 : 4;

3.1.12 Avoid evaluating Boolean conditions against true or false:


Ex:
Good:
if (!isValid)
{
//do something

http://dotnetdaily.net

Coding Standards for C#

Bad:
if (isValid == false)
{
//do something
}

3.1.13 Use switch/case statements for simple operations with parallel


conditional logic;
3.1.14 Prefer nested if/else over switch/case for short conditional sequences
and complex conditions;
3.1.15 Prefer polymorphism over switch/case to encapsulate and delegate
complex operations;

4. Code Commenting
Adding comments to your work is without doubt one of the most important factor in
team working. More than that, it also represents the best technique for keeping the
code maintainable in time. Have a look at rules below:

4.1 General Rules


4.1.1 All comments should be written in the same language, be grammatically
correct and contain appropriate punctuation;
4.1.2 Use // or /// but not /* */;
4.1.3 Do not use flower box comments
Ex:
//***************************
// flower box
//***************************

4.1.4 Use inline comments to explain assumptions, known issues and


algorithm insights;
4.1.5 Do not use inline comments to explain obvious code. Well written code
is self-documenting;
4.1.6 Always apply comment-blocks (///) to public, protected and internal
declarations:
http://dotnetdaily.net

10

Coding Standards for C#

Ex:
/// <summary>
/// Method used for saving customer's name
/// </summary>
/// <param name="name"></param>
public void SaveCustomerName(string name)

5. Exception Handling
As programmers we always want to write code of the highest quality. Unfortunate we are
not perfect so exceptions appear as a side effect of our code. Knowing that, we must not
punish the user of our product to see our mistakes. Please take a look at the following basic
rules about exception handling.

5.1 General Rules


5.1.1
5.1.2
5.1.3
5.1.4

Only catch exceptions that you can handle;


Avoid nesting try/catch within catch block;
Use finally block only for releasing used resources;
Always use validation to prevent the exception:
Ex:
Good:
if (status!=null && status.IsCompleted == true)
{
//some code here
}

Bad:
if (status.IsCompleted == true)
{
//some code here
}

5.1.5 Always add the [Serialize] attribute to exception classes;


5.1.6 Avoid re-throwing an exception;
5.1.7 Do not show important exception information to the client;

http://dotnetdaily.net

Anda mungkin juga menyukai