0% found this document useful (0 votes)
43 views

NET Coding Standards

Uploaded by

nttnitin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

NET Coding Standards

Uploaded by

nttnitin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

.

NET CODING STANDARDS


.NET DEVELOPMENT TEAM

June 2006

Jigar Acharya
Version: 0.4
Document Control
Amendment History

Document Revision Summary of Changes Author Release Date

0.1 Initial Draft Jigar Acharya 22-May-2006

0.2 Review Comments added Jigar Acharya 31-May-2006

0.3 Added extra code examples. Other Jigar Acharya 15-Jun-2006


minor changes done.

0.4 New sections added in Introduction. Jigar Acharya 30-Jun-2006


More examples provided.
Updated section “ASP.NET Web
11-Jul-2006
Applications / Web Services”
Work in progress.

Distribution List

Contact Company Contact Name Contact’s Role

Confidential © Skyward 2011 Page 2 of 46 .NET Coding Standards™


These Coding Standards…

are [indicative/preliminary drafts] only and [are accordingly subject to amendment and verification/must be modified as appropriate for
the relevant piece of work being undertaken][; and may contain bugs or inaccuracies that are latent or otherwise not discovered until
application of the relevant documentation or model in the required environment]. Accordingly: no warranties express or implied are
made as to their accuracy or suitability nor does Skyward accept any liability in respect of their use by any party for any purpose; and
the appropriate tests must be undertaken prior to their use.

must not be used without full understanding and proper consideration by or consultation with suitably qualified personnel;

are the confidential information and copyright of Skyward, must accordingly be kept confidential and may only be used by employees of
Skyward for the internal purposes of Skyward and to be amended for the purposes of its business; they may not otherwise be copied or
disclosed in whole or in part save without the express written consent of Skyward.

Confidential © Skyward 2011 Page 3 of 46 .NET Coding Standards™


Table of Contents
.NET CODING STANDARDS.................................................................................................................1
Document Control.................................................................................................................................2
Table of Contents..................................................................................................................................4
1 Introduction ........................................................................................................................................8
1.1 Background......................................................................................................................................8
1.2 Purpose.............................................................................................................................................8
1.3 Scope................................................................................................................................................8
1.4 Who should read this document.....................................................................................................9
1.5 How to use this document...............................................................................................................9
1.5.1 Document Structure..........................................................................................................9
1.5.2 Recommended usage.......................................................................................................9
2 General Guidelines...........................................................................................................................10
2.1 Naming styles.................................................................................................................................10
2.1.1 Pascal Casing.................................................................................................................10
2.1.2 Camel Casing..................................................................................................................10
2.1.3 Hungarian Notations........................................................................................................10
2.1.4 Upper Cased (All CAPS).................................................................................................10
2.2 General Naming Guidelines..........................................................................................................10
2.3 General Declaration Guidelines....................................................................................................11
3 Code formatting Guidelines.............................................................................................................11
3.1 Indentation......................................................................................................................................11
3.1.1 Code block indentation....................................................................................................11
3.1.2 Labels, “case” labels and “case” block contents..............................................................11
3.2 Whitespace usage..........................................................................................................................12
3.2.1 Spacing for method declarations.....................................................................................12
3.2.2 Spacing for method calls.................................................................................................12
3.2.3 Spacing for Brackets.......................................................................................................12
3.2.4 Spacing for delimiters......................................................................................................13
3.2.5 Spacing for operators......................................................................................................14
3.2.6 Other spacing options.....................................................................................................14
3.3 New Lines.......................................................................................................................................15
3.3.1 Line breaks for known constructs....................................................................................15
3.3.2 Wrapping Lines of Code..................................................................................................15
4 Common Code structures / Control of flow statements................................................................17
4.1 Simple statements..........................................................................................................................17
4.2 The “return” statement..................................................................................................................17
4.3 The “if” blocks................................................................................................................................17
4.4 The “for”, “foreach” loops............................................................................................................18

Confidential © Skyward 2011 Page 4 of 46 .NET Coding Standards™


4.5 The “while”, “do-while” loops.......................................................................................................18
4.6 The “switch" block.........................................................................................................................19
4.7 The “try-catch” blocks...................................................................................................................20
5 Coding conventions..........................................................................................................................21
5.1 Source files.....................................................................................................................................21
5.1.1 Guidelines in general.......................................................................................................21
5.2 Namespaces...................................................................................................................................21
5.2.1 Naming guidelines...........................................................................................................21
5.2.2 Declaration guidelines.....................................................................................................21
5.2.3 Usage guidelines.............................................................................................................21
5.3 Classes & Structs...........................................................................................................................21
5.3.1 Naming guidelines...........................................................................................................21
5.3.2 Declaration guidelines.....................................................................................................23
5.4 Class level Constants....................................................................................................................23
5.4.1 Naming guidelines...........................................................................................................23
5.4.2 Declaration guidelines.....................................................................................................23
5.5 Class level data members.............................................................................................................24
5.5.1 Naming guidelines...........................................................................................................24
5.5.2 Declaration guidelines.....................................................................................................25
5.5.3 Usage guidelines.............................................................................................................25
5.6 Class level events (Custom Events).............................................................................................25
5.6.1 Naming guidelines...........................................................................................................25
5.6.2 Declaration guidelines.....................................................................................................25
5.6.3 Usage guidelines.............................................................................................................25
5.7 Constructors & Destructors..........................................................................................................26
5.7.1 Naming guidelines...........................................................................................................26
5.7.2 Declaration guidelines.....................................................................................................26
5.7.3 Usage guidelines.............................................................................................................26
5.8 Methods..........................................................................................................................................26
5.8.1 Naming guidelines...........................................................................................................26
5.8.2 Declaration guidelines.....................................................................................................26
5.8.3 Usage guidelines.............................................................................................................27
5.9 Method Parameters / Arguments..................................................................................................27
5.9.1 Naming guidelines...........................................................................................................27
5.9.2 Usage guidelines.............................................................................................................27
5.10 Local variables.............................................................................................................................27
5.10.1 Naming guidelines.........................................................................................................27
5.10.2 Declaration guidelines...................................................................................................27
5.10.3 Usage guidelines...........................................................................................................27
5.11 Properties and Indexers..............................................................................................................27

Confidential © Skyward 2011 Page 5 of 46 .NET Coding Standards™


5.11.1 Naming guidelines for Properties..................................................................................27
5.11.2 Declaration guidelines...................................................................................................28
5.11.3 Usage guidelines...........................................................................................................28
5.12 Inner type declarations................................................................................................................30
5.12.1 Declaration guidelines...................................................................................................30
5.12.2 Usage guidelines...........................................................................................................30
5.13 Static members (Data members, Methods, Properties)............................................................30
5.13.1 Naming guidelines.........................................................................................................30
5.13.2 Declaration guidelines...................................................................................................30
5.13.3 Usage guidelines...........................................................................................................31
5.14 Interfaces......................................................................................................................................31
5.14.1 Naming guidelines.........................................................................................................31
5.14.2 Declaration guidelines...................................................................................................31
5.14.3 Usage guidelines...........................................................................................................32
5.15 Interface Members........................................................................................................................32
5.15.1 Naming guidelines.........................................................................................................32
5.16 Enumerations...............................................................................................................................32
5.16.1 Naming guidelines.........................................................................................................32
5.16.2 Declaration guidelines...................................................................................................33
5.17 Custom Delegates........................................................................................................................33
5.17.1 Naming guidelines.........................................................................................................33
5.17.2 Declaration guidelines...................................................................................................34
5.17.3 Usage guidelines...........................................................................................................34
5.18 Configuration data.......................................................................................................................34
5.18.1 Naming guidelines.........................................................................................................34
5.18.2 Declaration guidelines...................................................................................................35
6 Comments..........................................................................................................................................35
6.1 Commenting styles........................................................................................................................35
6.1.1 Single line comments......................................................................................................35
6.1.2 Block comments..............................................................................................................36
6.2 Document /File Header Comments...............................................................................................36
6.2.1 How it works....................................................................................................................36
6.3 Code Documentation Comments (XML).......................................................................................38
6.3.1 Types of documentation Tags.........................................................................................38
6.3.2 Setting up XML documentation properties for a project...................................................38
6.3.3 Examples.........................................................................................................................39
6.4 “TODO” comments........................................................................................................................39
6.4.1 When to use....................................................................................................................39
6.4.2 Configuring custom Task tokens.....................................................................................40
7 Implementation specific guidelines.................................................................................................41

Confidential © Skyward 2011 Page 6 of 46 .NET Coding Standards™


7.1 ASP.NET Web Applications...........................................................................................................41
7.1.1 Naming conventions........................................................................................................41
7.1.2 Other guidelines..............................................................................................................44
Table of Figures..................................................................................................................................46

Confidential © Skyward 2011 Page 7 of 46 .NET Coding Standards™


1 Introduction
1.1 Background
As part of the .NET programme in Skyward, there are several applications /services which have been
developed and /or maintained by the .NET Tech Team based in Mumbai. Although these applications /
services use various technologies, most of them have been developed using .NET. The list includes various
Web Applications, XML Web Services and Small Utility applications which cater to some important business
functions.
As the business progresses there are new Change Requests (CR’s) received and implemented. These CR’s
may include change of existing code/ configuration or addition of a totally new functionality. Considering the
importance of the .NET applications there is a need to define a set of coding standards and guidelines for the
.NET Tech team which will help manage the .NET applications / services better.

1.2 Purpose
The purpose of this document is to provide a Set of Coding Standards / Guidelines to the .NET Technical
team which will support development of new .NET Applications or re-factoring of existing .NET Applications
in the .NET Programme wherever applicable.

1.3 Scope
This coding standards document covers only essential areas as currently required for the .NET Technical
team. Although most of the specifications or guidelines given in this document are derived from Microsoft’s
specifications, amendments have been made where found necessary.
This document covers standards / guidelines for the following:
1. General Naming and Declaration guidelines.
2. Formatting of C# Code.
3. Naming, Declaration and Usage Guidelines for various known programming constructs in C#. E.g.
classes, interfaces, methods, properties etc.
4. Code Comments, Documentation comments and other miscellaneous guidelines.
It does not cover:
1. Coding standards for other .NET compliant languages (e.g. VB.NET in particular), even though
some guidelines may apply to these programming languages.
2. Standard Practices for specific type of solutions e.g. “Securing Web Services using WSE”. However
you may find references to such topics. A separate document for “Standard Practices” could be
launched in future.
3. Architecture or Design details of any .NET Application.
4. Recommendations for any SDLC processes.
Since the document is still evolving there are changes expected in terms of addition of new sections,
amendments to the existing sections and in some cases even deletion of existing sections.

Confidential © Skyward 2011 Page 8 of 46 .NET Coding Standards™


1.4 Who should read this document
All the members of the .NET .NET Development team will be the prime readers of this document. The team
currently includes Architects, Tech leads, Senior Developers, Developers and Trainees.
Although this document is targeted for .NET Tech Team, other departments of Skyward are welcome to
follow it these standards / guidelines if it suits their requirements.
By and large the readers of this document…
• Should be familiar with the concepts of Object Oriented Programming.
• Should be familiar with at least the Fundamental concepts of .NET.
• Should have hands-on experience with Web and / or Windows Applications Development using C#
and Visual Studio IDE (2003 or 2005).

1.5 How to use this document


1.5.1 Document Structure
The document divided into 6 major sections as discussed below.
• Section 2 – General Guidelines: covers naming Styles, generic guidelines for naming and
declaration of variables in C#.
• Section 3 – Code Formatting Guidelines: covers formatting guidelines e.g. indentation, spacing,
line breaks etc.
• Section 4 – Guidelines for Common Code Structures in C#: covers guidelines for common
control-of-flow statements in C#.
• Section 5 – Coding conventions for C# constructs: covers naming, declaration and usage
guidelines for almost all the constructs available in C# like Classes, Interfaces, Methods, Properties
etc.
• Section 6 – Commenting Guidelines: discusses commenting styles, Xml Code comments for C#
development.
• Section 7 – Guidelines for Web Application Development: Provides brief Naming, Declaration
and Usage guidelines for Web Development using ASP.NET.

1.5.2 Recommended usage


This document can be used as…
• A Handbook: Each of the above mentioned sections in the document is independent from the other
and hence it can be used as a quick reference handbook. One can search for the required topic in
the index and directly jump to the related section.
• A Consolidated Guide: Tech team members are advised to read the whole document at least once
as an effort has been made to cover all the important aspects of Coding Standards.
Note: You may find that some sections in the document which could have been placed in an Appendix,
however considering their importance it’s not been done so.

Confidential © Skyward 2011 Page 9 of 46 .NET Coding Standards™


2 General Guidelines
2.1 Naming styles
The section discusses various naming styles which will be referred in the later parts of this section. Some of
the most commonly used styles are as follows…

2.1.1 Pascal Casing


In this style the first letter of each word/term is capitalised. Use of underscores is discouraged.
Applies to: Type names, Methods or Properties, Events
E.g.: CustomerDetails, CreditCard, SendInformation

2.1.2 Camel Casing


In this style the first letter each word/term, except the first, is capitalised. Use of underscores is discouraged.
Applies to: local variables, non-public class members, method parameters
E.g.: loginName, password, userContextData

2.1.3 Hungarian Notations


This naming style has been in use for a long time and very useful to identify the type of any variable from its
name itself. The variable name is generally prefixed with a 2 to 4 letter abbreviation of its type. In some very
rare cases postfix strings are also used. The style uses camel casing. Use of underscores is discouraged
although it was quite common in C, C++ programming.
Applies to: Form Control Variables, Local variables of special types e.g. DataSet, DataRow
E.g.: ddlEmployees, btnSendForApproval, drPersmissionSet

2.1.4 Upper Cased (All CAPS)


Use all Upper case letters when declaring named constants. Since the letters used are all upper cased
underscores could be used to logically separate words/terms within the name.
Applies to: Named constants of a class, compilation constants
E.g.: PI, MAXIMUM_CHARS_ALLOWED, SERVICE_BUILD

2.2 General Naming Guidelines


• A name should be sensible enough to reflect the data stored in it.
• Avoid using abbreviations.
• At the same time do not let the name exceed 40 characters unless absolutely necessary and rightly
justified so.
• Avoid using underscores in the names unless it’s absolutely necessary.

Confidential © Skyward 2011 Page 10 of 46 .NET Coding Standards™


2.3 General Declaration Guidelines
• Declaration per line: One variable declaration per line is recommended as it encourages
commenting.
o E.g.: int count; // Count of chosen items
string frameCaption; //Caption for the Wizard frame

• Initialisation: if possible assign default values to the variable as they are declared.
o E.g.: int index = 0;

3 Code formatting Guidelines


3.1 Indentation
Indentation is one of the most important aspects of Coding standards. In earlier days of development
developers used spaces for indentation but it was never achieved successfully with spaces as some
preferred using 2 spaces and some preferred 4 spaces and others perhaps 8.
This guide strongly suggests use of TABS for code indentation for following reasons.
• Everyone can set their own preferred indentation level in the editor they use.
• It is only 1 character and not 2, 4, 8 … therefore it increases typing speed. Although not much but
space is saved (1 byte as opposed to 2 or 8 bytes for equivalent spaces).
• To increase or decrease indentation level, mark the required block, then increase indentation with
[Tab], or decrease it with [Shift-Tab].

3.1.1 Code block indentation


A thumb rule for indentation is that if a code block is surrounded with curly brackets ( ‘{‘ & ‘}’ ), indent its
contents. This applies to…
• Code inside the namespace declaration
• Code inside a Class, Struct, Enum or an Interface declaration.
• Code inside the Methods, Properties, Property Get & Set blocks.
• Code inside the if, for, foreach, while, do-while, switch, try-catch and similar blocks which use curly
brackets to define their body.

3.1.2 Labels, “case” labels and “case” block contents


• Indentation also applies to labels, “case” labels and contents of the “case” blocks inside switch which
don’t use curly brackets.

Confidential © Skyward 2011 Page 11 of 46 .NET Coding Standards™


3.2 Whitespace usage
Note: refer to Visual Studio 2005>Tools>Options>Text Editor>C#>Formatting>Spacing

3.2.1 Spacing for method declarations

3.2.1.1 Don’ts
• Don’t insert space between method name and its opening parenthesis
o int Method() is right
o int Method () is wrong.

• Don’t insert space within argument list parenthesis


o int Method(int input) it right
o int Method( int input ) is wrong

• Don’t insert space within empty argument list


o int Method() is right
o int Method( ) is wrong.

3.2.2 Spacing for method calls

3.2.2.1 Don’ts
• Don’t insert space between method name and its opening parenthesis
o Console.WriteLine("Step 1") is right
o Console.WriteLine ("Step 1") is wrong.

• Don’t insert space within argument list parenthesis


o Console.WriteLine("Step 1") is right
o Console.WriteLine( "Step 1" ) is wrong.

• Don’t insert space within empty argument list


o this.Show() is right
o this.Show( ) is wrong.

3.2.3 Spacing for Brackets

3.2.3.1 Don’ts
• Don’t insert space within empty square brackets
o string [] args is right
o string [ ] args is wrong

• Don’t insert space before open square bracket (except for declarations)
o itemArray[0] is right
o itemArray [0] is wrong

Confidential © Skyward 2011 Page 12 of 46 .NET Coding Standards™


• Don’t insert space within square brackets
o return list[0] is right
o return list[ 0 ] is wrong

3.2.3.2 Do’s
• Insert space before open square bracket during declarations
o string [] args is right
o string[] args is wrong

3.2.4 Spacing for delimiters

3.2.4.1 Don’ts
• Don’t insert space before or after dot
o return new System.Collections.ArrayList() is right
o return new System. Collections .ArrayList() is wrong

• Don’t insert space before comma


o int Add(int number1, int number2); is right
o int Add(int number1 , int number2); is wrong

• Don’t insert space before semicolon in a for statement


o for (int i = 0; i < 10; ++i) is right
o for (int i = 0 ; i < 10; ++i) is wrong

• Don’t insert space before colon for base or interface in type declaration
o class ProductService: IService is right
o class ProductService :IService is wrong

3.2.4.2 Do’s
• Insert space after colon for base or interface in type declaration
o class ProductService: IService is right
o class ProductService:IService is wrong

• Insert space after comma


o int Add(int number1, int number2); is right
o int Add(int number1,int number2); is wrong

• Insert space after semicolon in a for statement


o for (int i = 0; i < 10; i++) is right
o for (int i = 0;i < 10;i++) is wrong

Confidential © Skyward 2011 Page 13 of 46 .NET Coding Standards™


3.2.5 Spacing for operators

3.2.5.1 Don’ts
• Don’t insert spaces between a unary operator and its operand
o counter++ is right
o counter ++ is wrong

3.2.5.2 Do’s
• Insert spaces before and after the binary operators
o int result = 1 + 2 * 3 is right
o int result = 1+ 2*3 is wrong

3.2.6 Other spacing options

3.2.6.1 Don’ts
• Don’t insert space within parenthesis of expressions
o return a * (b - a) is right
o return a * ( b - a ) is wrong

• Don’t insert space within parenthesis of type casts


o (int)list[0] is right
o ( int )list[0] is wrong

• Don’t insert space after cast


o (int)list[0] is right
o (int) list[0] is wrong

• Don’t insert spaces inside parenthesis for control flow statements


o if (a > b) is right
o if ( a > b ) is wrong

3.2.6.2 Do’s
• Insert space after keywords in control flow statements
o if (a > b) is right
o if(a > b) is wrong

Confidential © Skyward 2011 Page 14 of 46 .NET Coding Standards™


3.3 New Lines
New Line breaks added apart from the ones forced by the compiler are very useful from code readability
perspectives. It also achieves logical separation of the code blocks.

3.3.1 Line breaks for known constructs


Use new line breaks for following…
• After a namespace name and before the opening bracket of the namespace body
namespace Skyward.TSM.DataAccess.General1
{
// namespace contents...
}

• After a class/struct/interface name and before the opening bracket of the class/struct/interface body
public interface IRenderer
{
//interface members...
}

• After a Method/Property name and before the opening bracket of the Method/Property body. Applies
to the Set and Get blocks within a property.
public static string GetConnectionString()
{
//Method body
}

• As discussed in the section “Common Code Structures / Control of Flow statements” later in the
document.

3.3.2 Wrapping Lines of Code


When an expression does not fit on a single line, break it up according to these general principles:
• Break after a comma.
• Break after an operator.
• Prefer higher-level breaks to lower-level breaks.
• Align the new line with the beginning of the expression at the same level on the previous Line
Example of breaking up method calls:
longMethodCall(expr1, expr2,
expr3, expr4, expr5);

1
 denotes new Line break

Confidential © Skyward 2011 Page 15 of 46 .NET Coding Standards™


Examples of breaking an arithmetic expression:
PREFER:
var = a * b / (c - g + f) +
4 * z;
BAD STYLE – AVOID:
var = a * b / (c - g +
f) + 4 * z;

The first is preferred, since the break occurs outside the parenthesized expression (higher level rule). Note
that you indent with tabs to the indentation level and then with spaces to the breaking position in our
example this would be:
> var = a * b / (c - g + f) +
> ......4 * z;

Where '>' are tab chars and '.' are spaces. (the spaces after the tab char are the indent with of the tab). A
good coding practice is to make the tab and space chars visible in the editor which is used.

Confidential © Skyward 2011 Page 16 of 46 .NET Coding Standards™


4 Common Code structures / Control of flow statements
This section describes how common code structures and control-of-flow statements are coded. Please mind
the formatting conventions (indentation, spacing, lining etc.) although they are explained in detail later in this
document.

4.1 Simple statements


• Each line should contain only one executable statement. Avoid using multiple declarations or
assignments in the same line.

4.2 The “return” statement


• A return statement should not use outer most parentheses.
o Don't use: return (n * (n + 1) / 2);
o Use: return n * (n + 1) / 2;

4.3 The “if” blocks


• The "if", "if-else", "if-else-if else" statements should look like this.
if (<condition>)
{
//Do this
}

if (<condition>)
{
//Do this
}
else
{
//Do that
}

if (<condition1>)
{
//Do this
}
else if (<condition2>)
{
//Do that
}
else
{
//Do something else
}

• If these blocks contain considerable number of lines, group them into regions or create sub routines/
methods and call them.

Confidential © Skyward 2011 Page 17 of 46 .NET Coding Standards™


• Even if the any of these blocks has only one line of code to execute put them into curly brackets. In
most cases we end up adding more lines in the block. Also this useful to clearly differentiate across
the logical blocks of execution.
if (!this.EmailExists(emailAddress))
{
inavalidEmails.Add(emailAddress);
}

In the above example there’s only one line of code to be executed if the specified condition is met.

4.4 The “for”, “foreach” loops


• A for statement should look like this…

for (int i = 0; i < items.Length; i++)


{
//body
}

• A foreach statement should look like this…

foreach (DataRow drEmployeeRow in dtEmployees.Rows)


{
//body
}

• If the body of the loop is deliberately kept empty, please add a comment specifying so. E.g.
for (int i = 0; i < errors.Count; errorMessage.Append(errors[i]), i++)
{
// Empty loop. Just preparing an error message
}

OR
// Empty loop. Just preparing an error message
for (int i = 0; i < errors.Count; errorMessage.Append(errors[i]), i++) ;

4.5 The “while”, “do-while” loops


• A while statement should look like this…
while (<condition>)
{
//body
}

Confidential © Skyward 2011 Page 18 of 46 .NET Coding Standards™


• A do-while statement should look like this…
do
{
//body
}
while (<condition>); //Please note the new line after the do block

• As discussed in the earlier sections, a while loop or a do-while loop, if kept empty should be
accompanied by relevant comments / explanations.

4.6 The “switch" block


• A switch statement should be of the following form. Note the formatting done.
switch (<expression>)
{
case <A>:
//block A
break;

case <B>:
//block B
break;

default:
//block default
break;
}
• Always provide the default block.

Confidential © Skyward 2011 Page 19 of 46 .NET Coding Standards™


4.7 The “try-catch” blocks
• A try-catch should look like this…
try
{
//guarded block
}
catch (Exception exp)
{
//Handle the exception
}

OR…
try
{
//guarded block
}
catch (Exception exp)
{
//Handle the exception
}
finally
{
//do the inevitable
}

Note: Explicitly specify the kind of exception object in case predictable. e.g. SQLException. For details on
exception handling refer to the later section in this document.

Confidential © Skyward 2011 Page 20 of 46 .NET Coding Standards™


5 Coding conventions
5.1 Source files
5.1.1 Guidelines in general
• Have one type declared per file. Although this is not mandatory, it helps the version control system
manage the files effectively. It also reduces the chances of conflicts in a multi user environment.
• Keep the name of the source file same as the Type name

5.2 Namespaces
5.2.1 Naming guidelines
• A namespace should form a logical package for the types contained in it and hence its name must
indicate the same.
• Use Pascal casing

5.2.2 Declaration guidelines


• Namespaces are usually nested just like folders so that all the types within the solution can be
organised properly.
• The usual format of a namespace hierarchy is…
<CompanyName>.<Product/Project>[.<Edition/Version>].<Layer>.<Custom>
E.g. namespace Skyward.TimesheetManager.Business.Workflow
Please note that although this is one declaration in total 4 namespaces have been declared, which
are:
• Skyward

• Skyward.TimesheetManager

• Skyward.TimesheetManager.Business

• Skyward.TimesheetManager.Business.Workflow

5.2.3 Usage guidelines


• When a class from any given namespace is to be referred in the code prefer declaring a
namespace import statement (the “using” statements) as opposed to using a FQCN (Fully
Qualified Class name).
E.g.: using System.Data.SqlClient;

• In case of ambiguities in class names across namespaces use the namespace alias in the
using statement and then use this alias to qualify the class.
E.g.: using SysConf = System.Configuration;
using BPAConf = Skyward.TSM.Utilities.Configuration;

5.3 Classes & Structs


5.3.1 Naming guidelines
A class or a struct name…

Confidential © Skyward 2011 Page 21 of 46 .NET Coding Standards™


• Must be a Noun or a Noun phrase
• Should use Pascal casing (Don’t use any Post or Pre fixes)
• Should always be SINGULAR in meaning unless required explicitly for a specific implementation.
E.g.: Product, ConfigurationManager, NotificationService

5.3.1.1 Special cases


In some cases class names could be modified to use a Prefix or a Postfix to provide a special meaning to it.
This section describes only few such cases e.g. in a typical application that follows a layered approach the
class names could also suggest the layer in which they reside.
A Technical Faculty should decide on the conventions to be followed for naming classes for a given project.

5.3.1.1.1 Abstract base classes


• A postfix like “Base” can be used for such classes. Any alternative word can be used as long as it
can convey that the class is an abstract class.
• E.g.: PageBase, NotificationServiceBase
Note: If the class is not abstract please do not use this convention.

5.3.1.1.2 Collection classes


• Names of Collection classes could have a postfix like “Collection”, “Set” or “List” based on the type of
functionality they provide.
• E.g.: EmployeeCollection, PermissionSet
o In the above example, the class EmployeeCollection indicates that it manages a collection of
type Employee which could be another entity class or a struct.
o Avoid using plural in the name of a collection class. “Employees” or “EmployeesCollection”
are invalid names as per this guide. If an instance of EmployeeCollection appears as a
Public member of a class (say Department), then the name “Employees” can be useful.

5.3.1.1.3 Event Argument classes


• Event Argument classes hold extra information about a specific event or a group of events. Its name
should predict the same.
• Use a postfix “EventArgs” for these classes.
• E.g.: NotificationEventArgs, ExpenseApprovalEventArgs

5.3.1.1.4 Custom Exception classes


• A custom exception class should use “Exception” as the postfix.
• E.g.: MailNotificationException, InvalidProductCostException

• For details please refer to the section “Exception Handling” later in this document.

5.3.1.1.5 Classes in Data Access/Service/ Business Layers


• Classes in these special layers/ class libraries can have postfixes as “Dalc”, “Service” as per
requirement.
E.g.: EmployeeService, EmployeeDalc

Confidential © Skyward 2011 Page 22 of 46 .NET Coding Standards™


5.3.2 Declaration guidelines
• Declare only one type per source file. It facilitates better version control of the types especially when
being accessed / modified simultaneously by many developers in the same team.
o In exceptional scenarios one can choose to have multiple types declared within the same
source file. E.g.
 If the new types created are temporary implementations for a quick fix or some trivial
changes which may not be needed in future.
 If the application design is not finalised for some part of implementation and has led
to creation of new types. These types should be moved to new files when the
application design is finalised.
• Although the framework & compiler allows working with “Orphan” classes, always declare the type
within a namespace earlier decided.
• Explicitly specify the visibility (public, internal) of the type. Code Behind files in ASP.NET 2.0 may be
considered as exceptions.

5.4 Class level Constants


5.4.1 Naming guidelines
A class level constant name…
• Must be Noun or a Noun phrase.
• Must use ALL CAPS. Use underscores to separate out words/terms. Must not have any prefix or
postfix.
• Should avoid any abbreviations or short forms.
E.g.: public const int MAXIMUM_CHARACTERS_ALLOWED = 256

5.4.2 Declaration guidelines


• Create a Separate region within the class for declaring class level constants. E.g.
• Declare the right type and access specifier for the constant variable.
#region Constants
/// <summary>
/// The maximum number of sheets allowed per book
/// </summary>
public const long MAXIMUM_SHEETS_PER_BOOK = 16;
#endregion

Confidential © Skyward 2011 Page 23 of 46 .NET Coding Standards™


• If a group of constants are identified which for some reason cannot be utilised as Enum Members
group them all under a static class. E.g.
public static class SectionNameConstants
{
#region Constants
/// <summary>
/// Path to the Logging Section
/// </summary>
public const string LOGGING = "/Logging";

/// <summary>
/// Path to the Mailer Section
/// </summary>
public const string MAILER = "/Mailer";

#endregion
}

5.5 Class level data members


5.5.1 Naming guidelines
Non-public data members
This applies to any private or protected data members defined within the class. Name of a non-public
data member…
• Must be Noun or a Noun phrase
• Should not use a plural form unless the variable represents an array or a collection.
• Must use Camel casing or Hungarian Notation (mostly applicable for form controls) depending on
the type. E.g.:
o private ILogger defaultLogger - Camel Casing
o protected TextBox txtFirstName - Hungarian Notation

• If specific private data member is exposed through a Property make sure that their names are same
except for the fact that the Property name will use Pascal casing.
Public or Internal data members
This applies to any data member declared as public or internal in the class. Although this is discouraged
there might be rare occasions when one may need to declare public data members. Name of a Public
data member…
• Must be Noun of a Noun Phrase
• Should not use a plural form unless the variable represents an array or a collection.
• Must use Pascal Casing

Confidential © Skyward 2011 Page 24 of 46 .NET Coding Standards™


5.5.2 Declaration guidelines
• Create a separate region for declaring the Private / Protected data members. Following region
structure could be followed
o “Data Members”
 “Private / Protected data members”
• “Form controls”
 “Public data members”
• “Events”

5.5.3 Usage guidelines


• While accessing the class level Members qualify them using the keywords “this” or “base”. Use of
such keywords clearly indicates the location of the member’s declaration/definition.
E.g. Use base.ViewState to indicate that it simply calls the base class implementation of the
“ViewState” property. Use this.ViewState to indicate that the current class has an overridden
version of “ViewState” implemented.
Please note that following such conventions is useful for understanding the code easily.

5.6 Class level events (Custom Events)


A class may provide a facility of notification through custom events. Please note that this section does not
describe the “Event Handler methods” but the Custom Events declared as Multi Cast Delegate event
variables.

5.6.1 Naming guidelines


Public Events:
A public event name…
• Must be a verb or a verb phrase
• Must use Pascal Casing
E.g.: public event EventHandler FormValidate

• In case the event happens to come in a pair of “Pre” and “Post” forms, use the Present (“… ing”) and
Past tense (“... [e]d”) forms of the verb respectively. E.g.…
o public event EventHandler FormValidating
o public event EventHandler FormValidated
Non-public events:
• Same as the Public Events. Note that this is a rare situation.

5.6.2 Declaration guidelines


• Declare all the custom events in a separate region within the class

5.6.3 Usage guidelines


• While accessing the class level events within the class qualify them using the keywords “this” or
“base”.

Confidential © Skyward 2011 Page 25 of 46 .NET Coding Standards™


• While raising the events always check for nulls as there may not be any Event Handlers assigned for
it. E.g.
if (this.FormValidated != null)
{
this.FormValidated(this, EventArgs.Empty);
}

5.7 Constructors & Destructors


5.7.1 Naming guidelines
• No real need for Naming conventions as the compiler enforces the rules.

5.7.2 Declaration guidelines


• Declare all the constructors in a separate region within the class.
• Always have a default constructor for your class.
• Provide as many overloaded constructors as possible to reduce number of lines in code while
instantiating the class.

5.7.3 Usage guidelines


• Avoid writing destructors as they cause a delay in garbage collection of instances of such a class.
Consider providing a Dispose method instead.
• Declare the constructors as private or internal if the class should not be instantiated explicitly.
• If the class need not be instantiated ever, consider declaring it as a static class. (.NET 2.0)

5.8 Methods
5.8.1 Naming guidelines
A Method name…
• Must be a Verb or a Verb phrase
• Must use Pascal casing
• Should avoid using short forms or abbreviations unless really required.
• Should indicate the type of work done. E.g. if a method returns a value consider starting its name
with “Get” or “Retrieve”. If it returns a Boolean consider starting its name with “Is”.
E.g.: InsertTimesheet, SendNotification, GetTotalLeaves

5.8.2 Declaration guidelines


• Declare all methods in a separate region. Create following sub-regions
o Private Methods
o Private /Protected methods – Event Handlers
o Public Methods

• Use the right access specifiers. Do not expose the members unnecessarily.

Confidential © Skyward 2011 Page 26 of 46 .NET Coding Standards™


5.8.3 Usage guidelines
• While accessing the methods of a class within the class qualify them using the keywords “this” or
“base” clearly indicating the place of their declaration/definition.
E.g.: this.ClearAllMessages(); or base.Close();

5.9 Method Parameters / Arguments


5.9.1 Naming guidelines
A method parameter name…
• Must be a Noun or a Noun phrase.
• Should not use a plural form unless the variable represents an array or a collection.
• Should be descriptive they are exposed through the assembly’s metadata (typelib).
• Must use Camel casing (don’t use Hungarian notations. E.g. consider naming a dataset parameter
as “employeeDataSet” instead of “dsEmployee”)

• Should avoid using short forms or abbreviations.


E.g.:
public void SendNotification(string senderEmailAddress, string subject,
string mailBody, int priority);

5.9.2 Usage guidelines


• Consider assigning a default value to output parameters. Even a null assignment is useful.

5.10 Local variables


5.10.1 Naming guidelines
A local variable name…
• Must be a Noun or a Noun phrase.
• Should not use a plural form unless the variable represents an array or a collection.
• Should be like ‘ctr’ or ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’ if used in trivial ‘while’ or ‘for’ loops.
• Must use Camel casing except for local variables of some types like DataSet, DataTable etc.

5.10.2 Declaration guidelines


• Have all the local variables declared in the beginning of the method. The exceptional cases may
include this: the local variables are to be used within explicitly defined contexts, created using the
“using” or similar code blocks.
• Consider assigning a default value along with the declaration if possible.

5.10.3 Usage guidelines


• Avoid using local variables for storing intermediate outputs if possible, especially the ones used for
writing minor debug messages during unit testing.

5.11 Properties and Indexers


5.11.1 Naming guidelines for Properties
A property name…

Confidential © Skyward 2011 Page 27 of 46 .NET Coding Standards™


• Should be a Noun or a Noun phrase
• Should not use a plural form unless the property represents an array or a collection.
• Must use Pascal casing.
• If a property wraps a private member of the same class, use the Pascal cased version of its name
for the property.

5.11.2 Declaration guidelines


• Declare all properties in a separate region. Create separate sub-regions for Private and Public
properties
• Consider declaring as many overloaded versions of an indexer as required in a custom collection
class.

5.11.3 Usage guidelines


• Consider using Properties instead of having a pair of “Get” and “Set” methods especially if there’s a
need for serialisation. Define a “set” block for a property only if it needs to be writable.
Examples
public string FirstName
{
get
{
return this.firstName;
}
set
{
this.firstName = value;
}
}
public string FullName //Read-only property
{
get
{
return string.Format("{0} {1}", this.firstName, this.lastName);
}
}

Confidential © Skyward 2011 Page 28 of 46 .NET Coding Standards™


public class QueryCollection: NameObjectCollectionBase
{
//Other class members
#region Indexers

/// <summary>
/// Searches for a query in the collection by the specified name
/// </summary>
/// <param name="key">The name of the Query</param>
/// <returns>Query reference if found ...</returns>
public Query this[string key];

/// <summary>
/// Returns a query in the collection at a specified position
/// </summary>
/// <param name="index">The index within the collection</param>
/// <returns>Query reference if found at ...</returns>
public Query this[int index];

#endregion
}

Confidential © Skyward 2011 Page 29 of 46 .NET Coding Standards™


5.12 Inner type declarations
5.12.1 Declaration guidelines
• Create a separate region named “Inner Types” towards the end of the class definition.
• Make sure that the inner type (Class / Interface / Enum) has appropriate modifiers / access
specifiers applied.

5.12.2 Usage guidelines


• Avoid declaring a type as an inner type if it is being used across many other classes within or
outside the library unless justified with specific requirement.
• A typical reason for creating inner classes could be to have logical grouping of members by
functionality.
Example:
public static class ConfigurationManager
{
#region Inner Classes

/// <summary>
/// Provides access to the config data in the "dataAcecss" section
/// </summary>
public static class DataAccessSection
{
public static string GetConnectionString();
public static string GetQueryConfigPath(HttpServerUtility server);
}

/// <summary>
/// Provides access to the config data in the "regionalOptions" section
/// </summary>
public static class RegionalOptionsSection;
{
public static DateTimeFormatInfo GetRegionalDateTimeFormatInfo();
public static string GetDefaultCurrencySymbol();
}

#endregion
}

5.13 Static members (Data members, Methods, Properties)


5.13.1 Naming guidelines
• Static Data Members: Follow the Naming guidelines as given earlier for non-static data members.
o However don’t using Hungarian notations for any type of data member.

• Static Methods: Follow the Naming guidelines as given earlier for non-static Methods.
• Static Properties: Follow the Naming guidelines as given earlier for non-static Properties.

5.13.2 Declaration guidelines


• Create a separate region named “Static Members”. Have separate sub regions created for Data
Members, Methods and Properties.

Confidential © Skyward 2011 Page 30 of 46 .NET Coding Standards™


5.13.3 Usage guidelines
• Identifying potential static members and declaring them as static may improve the performance of
the application a lot. E.g. Static constructors could be a useful place to write the environment
initialisation code.
• Typical implementations of classes like “ConfigurationManager”, “PoolManager” are good examples
of how static members can be used effectively.
Example:
public class ServicePoolManager
{
private static long activePoolsCount;

public static long ActivePoolsCount


{
get
{
return ServicePoolManager.activePoolsCount;
}
}

public IServicePool CreatePool(string servicePoolName, IService service)


{
// Implementation for Create Pool
}

public IServicePool Activate(string servicePoolName)


{
// Implementation for Activate Pool
ServicePoolManager.activePoolsCount++;
}

public IServicePool Release(string servicePoolName)


{
// Implementation for Release Pool
ServicePoolManager.activePoolsCount--;
}
}

5.14 Interfaces
5.14.1 Naming guidelines
An interface name…
• Must be a Noun, Noun phrase or Adjective describing a specific behaviour
• Should use “I” as the prefix to indicate that it’s an interface

• Must use Pascal Casing


E.g.: IServiceResponse, ICommandRouter, IUserContext

5.14.2 Declaration guidelines


• Declare only one interface per source file.
• Declare in an appropriate namespace earlier decided.

Confidential © Skyward 2011 Page 31 of 46 .NET Coding Standards™


5.14.3 Usage guidelines
• Consider having interfaces in an independent Class library especially when used in distributed
environment.

5.15 Interface Members


5.15.1 Naming guidelines
• Use the same guidelines used for Class Members
Example:
namespace Skyward.BPA.EPDA2.ServiceBroker
{
public interface IServiceController
{
ICommand GetCommand(string commandName);
IServiceResponse Invoke(ICommand command);

}//end IServiceController
}//end namespace ServiceBroker

5.16 Enumerations
5.16.1 Naming guidelines
An Enum name…
• Should be a Noun or a Noun phrase.
• Should use Pascal casing.
• Should avoid using a plural form in the name even if the Enum represents a group of values.
o E.g. consider “ViewMode” instead of “ViewModes”.
An Enum Value name…
• Should be a Noun or a Noun Phrase unless the value itself represents otherwise as per business
rules.
• Should use Pascal casing. Do not use any prefix or a postfix.
• Do not repeat any part of the Enum name in the Value name. E.g. “ViewMode.Read” is better than
“ViewMode.ReadMode”. (All values in ViewMode are basically Modes)

Confidential © Skyward 2011 Page 32 of 46 .NET Coding Standards™


Example:
public enum ViewMode: byte
{
/// <summary>
/// Indicates Read permission
/// </summary>
ReadOnly,

/// <summary>
/// Indicates Read & Write permissions
/// </summary>
ReadWrite,

/// <summary>
/// Indicates No Access
/// </summary>
None
}

5.16.2 Declaration guidelines


• Have one enumeration declared per source file.
• Specify the base type for the Enum explicitly if required. The default base is “int”.

• Have values assigned explicitly to Enum Value members only if necessary.

5.17 Custom Delegates


5.17.1 Naming guidelines
A delegate name…
• Must be of the form: <EventName>EventHandler where “EventName” should be a Noun or a Noun
phrase representing an event for which the delegate is created. Make sure that with this convention
the name does not exceed 40 characters in length.
E.g.:

Delegate declaration:
public delegate void NotificationEventHandler(object sender,
NotificationEventArgs e);
Event declaration:
public event NotificationEventHandler Notify;

• In .NET2.0 the EventHandler delegate is templated to work with any “EventArgs” based class.
Hence there is no special need to create a custom delegate as given above. The same can be
implemented as follows.

Event declaration:
public event EventHandler<NotificationEventArgs> Notify;

Confidential © Skyward 2011 Page 33 of 46 .NET Coding Standards™


5.17.2 Declaration guidelines
• If the delegates are public and used across the classes then declare it in an independent source file.
• In cases where the delegates are used for internal event handling, they can be declared as inner
classes.

5.17.3 Usage guidelines


• As explained earlier while working in .NET2.0 there’s no real need for working with custom delegates
if the Event implementation is typical.

5.18 Configuration data


When working with a large amount of configuration information for an application the well known sections like
“appSettings” and “connectionStrings” are not useful. In such cases Custom sections are useful to group the
pieces together.

5.18.1 Naming guidelines

5.18.1.1 Custom Section names


A custom section name or a section group name…
• Should be a noun or a noun phrase
• Should use Camel casing.
E.g.: cultureSettings, pageUrls, defaulLogging

5.18.1.2 Custom Attribute names


If one needs to work with a custom xml structure to store the required configuration data in the config file,
he/she can create a custom section handler (implementing IConfigurationSectionHandler). In this
case the author of this custom section handler should follow the naming guidelines given below.
A custom attribute name…
• Should be a Noun or a Noun phrase
• Should use Camel casing
• Should be singular in meaning if the attribute value contains one unit of config info.
E.g.
sender="[email protected]".
Here the attribute value provides one email address.
• Could be plural in meaning if the attribute value contains more than one values usually delimited by
a character or a pattern. This practice is discouraged.
E.g.
recipients="[email protected]; [email protected]"
Here the attribute value provides 2 email addresses separated by semicolon.

Confidential © Skyward 2011 Page 34 of 46 .NET Coding Standards™


5.18.1.3 Key names
In some of the well known sections like appSettings and connectionStrings, user specifies a key
name and then a value in each entry. By nature they happen to be attribute values and should follow these
guidelines.
A Key name…
• Should be a Noun or a Noun phrase
• Should use Pascal Casing. E.g.
o A sample entry in appSettings section should look like this…
<add key="PortalSiteUrl" value="http://www.acmesolutions.co.uk"/>
o A sample entry in connectionStrings section should look like this…
<add name="StateDatabase" connectionString="Data Source=SERV..."/>

5.18.2 Declaration guidelines


• Declare the configSections section right at the top of the configuration file.

• Declare the appSettings and the connectionStrings sections right at the bottom of the
configuration file.
• Declare all the custom sections in between. Have a starting and ending XML comment block for
each section describing what’s held in it.

6 Comments
Terms revisited:
• Comment: A comment can be referred to a useful note added along with the code to provide some
useful information which is ignored by the source code compiler. (Although some special comments
are treated differently by some compilers. E.g. C# documentation comments)
• Commented Code: This can refer to any part of the source code which is commented out so that it
will not be used by the source code compiler.
Note: Ideally a fully matured code should not have any “commented code” but only “comments”.

6.1 Commenting styles


6.1.1 Single line comments
• Use the // comment style to "comment out" code (shortcut in VS: Ctrl+K, Ctrl+C). It may be used for
separating sections of code too. Single line comments must be indented to the indent level when
they are used for code documentation. Commented out code should be commented out in the first
line to enhance the visibility of commented out code.
• A thumb rule says that generally, the length of a comment should not exceed the length of the code
explained by too much, as this is an indication of too complicated, potentially buggy, code. But many
a times this cannot be avoided as source codes always evolve and mature over time.
E.g:
//Read the Config information from ePlanning Config file
string configFilePath = ConfigurationManager.GetConfigFilePath(server);

Confidential © Skyward 2011 Page 35 of 46 .NET Coding Standards™


6.1.2 Block comments
• Block comments should usually be avoided. For descriptions use of the “///” comments to give C#
standard descriptions is recommended. When you wish to use block comments you should use the
following style:
#region Explanation for Some Logic
/* Line 1
* Line 2
* Line 3
*/
#endregion

o This will set off the block visually from code for the (human) reader. Surrounding such
comment blocks within regions is quite useful.

• Alternatively one might use the old fashioned C style for single line comments, even though it is not
recommended. In case you use this style, a line break should follow the comment, as it is hard to
see code preceded by comments in the same line.
if (condition1) /* && <condition2>)*/
{
//do something...
}
o This type of comment should be used only for temporary purposes and for code only. E.g.
while conducting unit test to test specific piece of code.

6.2 Document /File Header Comments


For any source file the header information is always useful if it provides complete details of…

• When the file was created


• Who created it
• Who modified it last
• When it was modified.

Since CVS will be used for Source Code Control, we’ll use facilities of one of its client i.e. WinCVS by which
it can update any text/ASCII based file with the latest information of it as shown above.

6.2.1 How it works

• WinCVS provides a feature of WinCVS variables like Source, Date and Author which supply the
respective information during a commit operation.
• While committing a Text/ASCII file into CVS using WinCVS, WinCVS retrieves the current value of
the used variable and replaces all its occurrences in the file with this value.
• E.g. if a text file has following block defined somewhere in it…

//$Source: $
//$Date: $
//$Author: $

• During the next commit operation the block will be modified as follows…

Confidential © Skyward 2011 Page 36 of 46 .NET Coding Standards™


//$Source: /cvs/ZOP-TSM-D04/readme.txt,v $ path of the file in CVS repository
//$Date: 2005/11/04 10:49:01 $ Date and time of commit
//$Author: john.woods $ CVS username of the user who committed

• Please also note that creating such a header is one time activity and required only when a file is
committed for the first time. Subsequent CVS commits will automatically update the variable values.
• Every Source file hence will always have a header as shown in sections below (right before anything
else in the file). This might differ slightly based on the type of file used.
• For a C# source file

/// <path>$Source: $</path>


/// <created>17 Nov 2004</created>
/// <createdBy>John Woods</createdBy>
/// <lastModified>$Date: $</lastModified>
/// <lastModifiedBy>$Author: $</lastModifiedBy>

• After the next commit into CVS,


• For a Web.config, App.config or any xml file. (Note that the first line here is an XML declaration
as required by any XML document.)

<?xml version="1.0" encoding="utf-8" ?>


<!--
<path>$Source: $</path>
<created>10 Dec 2005</created>
<createdBy>Clint White</createdBy>
<lastModified>$Date: $</lastModified>
<lastModifiedBy>$Author: $</lastModifiedBy>
-->

• For ASPX, ASCX, ASMX files

<%@ Control Language="c#" ...%>


<%
/************* Please Do not remove this section *****************
<path>$Source: $</path>
<created>4 Aug 2005</created>
<createdBy>John Woods</createdBy>
<lastModified>$Date: $</lastModified>
<lastModifiedBy>$Author: $</lastModifiedBy>
*****************************************************************/
%>

• For static content & script files (HTML, JS, CSS etc)
o Unfortunately we cannot use the same feature for these files are they are served “as-is” to
the web clients by the Web server. We would not want confidential information about the
document to be sent over to the web client that way.

Confidential © Skyward 2011 Page 37 of 46 .NET Coding Standards™


6.3 Code Documentation Comments (XML)
In the .net framework, Microsoft has introduced a documentation generation system based on XML
comments. These comments are basically C# “///” comments containing XML tags.

6.3.1 Types of documentation Tags


These tags come in the following categories
1. Core Documentation tags: Tags like <summary/>, <param/> & <exception/> fall into this
category. They represent information of various components of source code which is woven into the
Type Library information for the assembly. This is basically the same information that’s available
from the object browser and is used by the IDE for IntelliSense.
These must be applied to all the code elements which are visible from Object Browser.
2. Formatting / referencing tags: Tags like <code/>, <list/>, <para/> fall into this category.
They govern the layout of the documentation

6.3.2 Setting up XML documentation properties for a project


Setting up XML documentation properties is absolutely necessary in case of Class library projects. In both
versions of Visual Studio this can be set from [Project] Properties > Build >Xml Documentation File.
Please note that the primary name of the Xml File must be same as that of the assembly.

• In Visual Studio.NET 2003

Figure 1 - Xml Documentation properties in VS.NET 2003

• In Visual Studio 2005

Figure 2 - Xml Documentation properties in VS 2005

The compiler creates/updates the specified xml file with all the Xml Documentation comments inserted the
source files of the project. Warnings are displayed if there are no comments available for the members
visible from type library (metadata). Tools like NDoc can be used for creating standard class library help files
in various known styles (JavaDoc, MSDN or Custom).

Confidential © Skyward 2011 Page 38 of 46 .NET Coding Standards™


6.3.3 Examples
Following are some examples of code documentation comments.

• Class declaration
/// <summary>
/// The exception thrown when an error occurs in Download.
/// </summary>
public class DownloadException: ApplicationException
{
private FileInfo fileInfo;
public DownloadException(FileInfo fileInfo, string errorMessage)...
}

• Method declaration
/// <summary>
/// Initiates a File Download for the given file
/// </summary>
/// <param name="filePath">Physical path of the file on the web server</param>
/// <param name="response">Reference to the HttpResponse object</param>
/// <exception cref="DownloadException">This exception is thrown if the
specified file not found on the web server</exception>
/// <remarks>The method clears the current Response before initiating a
download</remarks>
public static void InitiateFileDownload(string filePath, HttpResponse response)
{
//method implementation goes here...
}

6.4 “TODO” comments


6.4.1 When to use
We all face situations when a particular module or sometimes a whole application has to be developed,
tested and deployed in very unrealistic timelines. Although not preferred in such situations, due to time
pressures developers may compromise on the coding standards. The TODO comments prove very useful in
such times.
Developers can insert TODO comments to specify a pending task in coding. Since these comments have a
specific format the Visual Studio can recognise them as tasks which can be viewed from the Task List
window. A typical TODO comment looks like this…
try
{
//Trivial Code
}
catch(Exception exp)
{
//TODO: Need not be handled. Consider logging this as a warning
}

• Please note that the comment must be start with two forward slashes followed by the word TODO,
the colon as shown above. Visual Studio identifies this as a token.

Confidential © Skyward 2011 Page 39 of 46 .NET Coding Standards™


6.4.2 Configuring custom Task tokens
Custom task tokens can be created in Visual Studio (both versions).
Tools->Options->Environment->Task List

Figure 3 - Configuring custom tokens in Visual Studio


As shown in the image above, tokens like REVIEWER and REVIEWEE can be used during code reviews.
E.g. consider that the code reviewer adds the following comment on a line…
//REVIEWER:AK: Consider naming this variable as sqlStatement instead.
string strSql = "SELECT * FROM ProductTypes";

If the Author of this source file has the custom token “REVIEWER” setup in his/her IDE, the task list will show
it up as a task as follows.

Figure 4 - Custom tasks shown in the Task List Window


The user can simply double click on the task and the IDE will navigate him/her to the location.

Confidential © Skyward 2011 Page 40 of 46 .NET Coding Standards™


7 Implementation specific guidelines
7.1 ASP.NET Web Applications
7.1.1 Naming conventions

7.1.1.1 Web Pages (ASPX)

• Use short but meaningful names for the aspx pages as the end user will use see these.
• Use Pascal naming convention as their code-behind classes will also use the same name
• E.g. CreateUser.aspx, Login.aspx, Order.aspx.

7.1.1.2 Web User controls (ASCX)

7.1.1.2.1 Views

• Postfix the word “View” to indicate its role. One should be able to relate to its parent ASPX page by
name.
• Use Pascal naming convention
• E.g. CreateUserView, CreateUserErrorView, CreateUserSuccessView.

7.1.1.2.2 Controllers

• Postfix the word “Controller” to indicate that it’s a controller.


• Use Pascal naming convention
• E.g. CreateUserController

7.1.1.2.3 Consuming a User Control


Consider the following example.
<%@ Page Language="C#" ... %>
<%@ Register Src="~/Common/Header.ascx" TagName="Header" TagPrefix="tsm" %>
<%@ Register Src="~/Common/Footer.ascx" TagName="Footer" TagPrefix="tsm" %>

• Always have the “@ Page“ declaration above all.


• Use a Web App relative path instead of a Document relative path.
o Src="~/Common/Header.ascx"
• Have the TagName same as the Control Name.
• Change the TagPrefix to use a name which will represent the logical group to which the control
belongs.
o TagPrefix="tsm"
• Use this tag prefix during control instance declaration
o <tsm:Header ID="header" runat="server" />

Confidential © Skyward 2011 Page 41 of 46 .NET Coding Standards™


7.1.1.3 Controls & variables
Set the IDs of the form controls and variables of some commonly used types based on the tables
given below.
Common Form Controls

Type Prefix (lowercase)

Label lbl

Literal lit

TextBox, HtmlInputText, HtmlTextArea, txt


HtmlInputPassword

HiddenField, HtmlInputHidden hid

DropdownList, HtmlSelect (Dropdown Style) ddl

ListBox, HtmlSelect (List box style) lst

CheckBox, HtmlInputCheckBox cb

CheckBoxList cbl

RadioButton, HtmlRadioButton rb

RadioButtonList rbl

Button, HtmlInputButton, HtmlInputSubmit, btn


HtmlInputReset

ImageButton ibtn

LinkButton lbtn

HyperLink, HtmlAnchor hl

Image, HtmlImage img

ImageMap imap

Calendar cal

FileUpload, HtmlInputFile fupl

AdRotator adr

Confidential © Skyward 2011 Page 42 of 46 .NET Coding Standards™


Container Controls

Type Prefix (lowercase)

Table, HtmlTable tbl

TableRow, HtmlTableRow tr

TableCell, HtmlTableCell td

Panel pnl

Div div

View vw

MultiView mvw

PlaceHolder ph

Validation Controls

Type Prefix (lowercase)

RequiredFieldValidator rfv

RegularExpressionValidator rev

RangeValidator rv

CompareValidator cmpv

CustomValidator cstv

ValidationSummary vs

Data Controls/Variables

Type Prefix (lowercase)

DataGrid dg

DataList dl

GridView gv

Repeater rptr

FormView fvw

DetailsView dvw

SqlDataSource, AccessDataSource, ObjectDataSource dsrc

Xml xml

DataSet ds

Confidential © Skyward 2011 Page 43 of 46 .NET Coding Standards™


Type Prefix (lowercase)

DataRelation drel

DataTable dtbl

DataView dvw

DataRow drw

SqlDataReader, OleDbDataReader drdr

SqlDataAdapter, OleDbDataAdapter da

Navigation Controls

Type Prefix (lowercase)

SiteMapPath smp

Menu mnu

TreeView tvw

Provide meaningful names to the control variables.

7.1.2 Other guidelines

• Avoid putting code in ASPX files of ASP.NET. All code should be in the code-behind class.
• Code in code behind class of ASP.NET should call other components rather than contain direct
business logic.
• In both ASP.NET pages and web services, wrap session variables in local properties such that only
these properties will access the session variable and the rest of the code will use these properties
only.
• Avoid setting the Auto-Postback property to “true” for server controls in ASP.NET.
• In transactional pages or web services, it is recommended to store session in Database.
• Turn on Smart Navigation for ASP.NET pages.
• Strive to provide interfaces for web services
• Always provide namespace and service description for web services.
• Always provide a description for web methods.
• When adding a web service reference, provide a meaningful name for the location.(use host IP
Addresses such that change in Deployment becomes easier)
• Always modify client-side web service wrapper class to support cookies.
• The “InitializeComponent” method (ASP.NET1.1): The InitializeComponent method which is
created by default for ASPX and ASCX code-behind classes, contains lines which initialise event
handlers for many events like page loads, button clicks etc. Due to a bug in Visual Studio.NET 2003,
many a times when the developer switches to Design mode, these lines are removed. We can use
the following solution …

Confidential © Skyward 2011 Page 44 of 46 .NET Coding Standards™


• Create a new method “InitializeEventHandlers” of the same signature as that of the
InitializeComponent method, move all the event handler declarations from InitializeComponent
to this method.

private void InitializeComponent()
{
}

public void InitializeEventHandlers()


{
this.Load += new System.EventHandler(this.Page_Load);
this.btnConfirm.Click += new System.EventHandler(this.btnConfirm_Click);
}

• Call it explicitly in the OnInit after the InitializeComponent method call.

override protected void OnInit(EventArgs e)


{
InitializeComponent();
InitializeEventHandlers();
base.OnInit(e);
}

Confidential © Skyward 2011 Page 45 of 46 .NET Coding Standards™


Table of Figures
Figure 1 - Xml Documentation properties in VS.NET 2003...............................................................38
Figure 2 - Xml Documentation properties in VS 2005.......................................................................38
Figure 3 - Configuring custom tokens in Visual Studio....................................................................40
Figure 4 - Custom tasks shown in the Task List Window.................................................................40

Confidential © Skyward 2011 Page 46 of 46 .NET Coding Standards™

You might also like