Guidelines C# Coding Standards
Sign in

Guidelines C# Coding Standards

Project Leader

Guidelines C# Coding Standards.docx

Introduction

Believe it: majority of the programmers write "working code," but not "efficient code." As we mentioned in the beginning of this tutorial, do you want to become the "Most Valued Professional" of company ? Writing "efficient code" is an art that you must learn and practice.

The goal is to define guidelines to enforce consistent style and formatting and help developers avoid common pitfalls and mistakes. Specifically, this document covers Naming Conventions, Coding Style, Language Usage, and Object Model Design

Naming Conventions

(Use pascal case in class name Camel case in variable or method name)

Pascal casing: the first character of all words is upper case and the other characters are lower case.

Camel casing: the first character of all words, except the first word, is upper case and other characters are lower case.

Use Pascal casing for class names ,method names and Use Camel casing for variables and method parameters:

Example ::

public class HelloWorld

{

int totalCount = 0;

void SayHello(string name)

{

string fullMessage = "Hello " + name;

... }}

Do not use Hungarian notation to name variables. mean having the data type as a prefix for the variable name and using m_ as the prefix for member variables, e.g:

Example ::

string m_sName;

int nAge;

However, in .NET coding standards, this is not recommended. Usage of data type and M_ to represent member variables should not be done. All variables should use Camel casing. Use meaningful, descriptive words to name variables:

Do not use abbreviations. Use name, address, salary etc. instead of nam, addr, sal.

Do not use single character variable names like i, n, x, etc. Use names like index and temp.

One exception in this case would be variables used for iterations in loops:

 

Example ::

for ( int i = 0; i < count; i++ )

{

...

}

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

Do not use underscores (_) in variable names.

 

Namespace names should follow the standard pattern.

[]..

Example : testApp.Admin.visitorlist.aspx

File name should match with class name. For example, for the class HelloWorld, the file name should be helloworld.cs (or helloworld.vb).

see below screen has some metrix for Naming Conventions

 

Best Practices for Coding

(Think 1 min atlest before write a code then it will be short and good code )

Avoid having too-large files. If a file has more than 300-400 lines of code, you must consider refactoring the code into helper classes. Avoid writing very long methods. A method should typically have 1-25 lines of code. If a method has more than 25 lines of code, you must consider refactoring it into separate methods. The method's 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.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.

 

Good

// Save the address.

SaveAddress ( address );

// Send an email to the supervisor to inform that the address is updated.

SendEmail ( address, email );

void SaveAddress ( string address ) { }

void SendEmail ( string address, string email ) { }

 

Not good:

// Save address and send an email to the supervisor to inform that the address is updated.

SaveAddress ( address, email );

void SaveAddress ( string address, string email )

{ // Save the address. // Send an email to inform the supervisor that the address is changed. }

 

Use the C# or VB.NET specific types, rather than the alias types defined in the System namespace.

int,string ,object not like Int16 ,String ,Object etc

 

Do not hardcode numbers. Use constants instead (Enum).

Do not hardcode strings. Use resource files.

Do not make the member variables public or protected. Keep them private and expose public/protected properties. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path. Never assume that your code will run from drive C:. You never know; some users may run it from a network or from a Z:.

Show short and friendly messages to the user, but log the actual error with all possible information.

Commenting Conventions

(write clean, readable code in such a way that it doesn't need any comments to understand it)

Place the comment on a separate line, not at the end of a line of code.

Begin comment text with an uppercase letter.

End comment text with a period.

Do not create formatted blocks of asterisks around comments.

Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.

 

// The following declaration creates a query. It does not run

// the query.

 

Do not write comments for every line of code and every variable declared. Write comments wherever required. Good, readable code will require very few comments. If all variables and method names are meaningful, that will make the code very readable and it will not need much commenting. Fewer lines of comments will make the code more elegant. However, if the code is not clean/readable and there are fewer comments, that is worse. If you have to use some complex or weird logic for any reason, document it very well with sufficient comments. If you initialize a numeric variable to a special number other than 0, -1, etc., document the reason for choosing that value.Do a spell check on comments and also make sure that proper grammar and punctuation are used.

 

Layout Conventions

Good layout uses formatting to emphasize the structure of your code and to make the code easier to read. Microsoft examples and samples conform to the following conventions:

Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see Options,Text Editor, C#, Formatting.

If continuation lines are not indented automatically, indent them one tab stop (four spaces).

Add at least one blank line between method definitions and property definitions.

Use parentheses to make clauses in an expression apparent, as shown in the following code.

if ((val1 > val2) && (val1 > val3))

{

// Take appropriate action.

}

Try-catch and using Statements in Exception Handling

Use a try-catch statement for most exception handling.

Do not write catch exception with do nothing. If you hide an exception, you will never know if the exception happened or not. In the case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, the method and class name, etc. Always catch only the specific exception, not generic exceptions.

Do not write very large try-catch blocks. If required, write a separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error messages to the user.You may write your own custom exception classes, if required, in your application. Do not derive your custom exceptions from the base class SystemException. Instead, inherit from ApplicationException.

Simplify your code by using the C# using statement. If you have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using statement instead.

// You can do the same thing with a using statement.

using (Font font2 = new Font("Arial", 10.0f))

{

byte charset = font2.GdiCharSet;

}

Language Usage

Avoid putting multiple classes in a single file

Always place curly braces ({ and }) on a new line.

Do not omit access modifiers. Explicitly declare all identifiers with the appropriate access modifier instead of allowing the default.

Example:

// Bad!

Void WriteEvent(string message)

{…}

// Good!

private Void WriteEvent(string message)

{…}

 

Try to initialize variables where you declare them.

Always choose the simplest data type, list, or object required.

Always use the built-in C# data type aliases, not the .NET common type system (CTS).

 

Example:

short NOT System.Int16

int NOT System.Int32

long NOT System.Int64

string NOT System.String

 

Only declare member variables as private. Use properties to provide access to them with public,

protected, or internal access modifiers.

 

Try to use int for any non-fractional numeric values that will fit the int datatype - even variables for nonnegative numbers.

Only use long for variables potentially containing values too large for an int.

Try to use double for fractional numbers to ensure decimal precision in calculations.

Only use float for fractional numbers that will not fit double or decimal.

Avoid using float unless you fully understand the implications upon any calculations.

Try to use decimal when fractional numbers must be rounded to a fixed precision for calculations. Typically

this will involve money.

Avoid using sbyte, short, uint, and ulong unless it is for interop (P/Invoke) with native libraries.

Try to use the “@” prefix for string literals instead of escaped strings.

Check list:

Naming Conventions

  • Use Pascal casing for class names ,method names and Use Camel casing for variables and method parameters

  • Do not use Hungarian notation to name variables.

  • Do not use abbreviations. Use name, address, salary etc. instead of nam, addr, sal.

  • Do not use single character variable names like i, n, x, etc. Use names like index and temp.

  • Do not use underscores (_) in variable names.

  • Namespace names should follow the standard pattern.

 

Best Practices for Coding

  • Avoid having too-large files, Split the file in multiple class if needed, or use partial class.

  • Specific types, rather than the System namespace.

  • Do not hardcode numbers. Use constants instead (Enum).

  • Do not hardcode strings. Use resource files.

  • Do not make the member variables public or protected

 

Commenting Conventions

  • Begin comment text with an uppercase letter.

  • Place the comment on a separate line, not at the end of a line of code.

 

Layout Conventions

  • Add at least one blank line between method definitions and property definitions.

  • Always place curly braces ({ and }) on a new line.

 

Try-catch and using Statements in Exception Handling

  • Simplify your code by using the C# using statement

  • Use a try-catch statement for most exception handling.

  • Do not write catch exception with do nothing

 

Language Usage

  • Avoid putting multiple classes in a single file

  • Try to initialize variables where you declare them.

  • Always choose the simplest data type, list, or object required.

  • Avoid using sbyte, short, uint, and ulong unless it is for interop (P/Invoke) with native libraries.

  • Try to use the “@” prefix for string literals instead of escaped strings.

 

 

9 /10

prevnew
start_blog_img