Knowledge Share
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Knowledge Share

Knowledge is NOT Power IMPLEMENTATION of knowledge is Power!!!
 
HomePortalGalleryLatest imagesRegisterLog in

 

 Coding Conventions in .net

Go down 
AuthorMessage
Admin
Admin



Posts : 142
Points : 59554454
Reputation : 0
Join date : 2007-12-29
Location : Chennai

Coding Conventions in .net Empty
PostSubject: Coding Conventions in .net   Coding Conventions in .net Icon_minitimeMon Dec 31, 2007 11:58 am

.Net Coding
Guidelines and Standards




Relationship to the Common Type System and the Common Language Specification 2
Naming Guidelines 3
Naming Conventions 3
General Guidelines 3
Code Commenting 4
Capitalization Styles 4
Case Sensitivity 5
Abbreviations 6
Avoiding Type Name Confusion 8
Namespace Naming Guidelines 10
Interface Naming Guidelines 11
Attribute Naming Guidelines 12
Enumeration Type Naming Guidelines 12
Static Field Naming Guidelines 12
Parameter Naming Guidelines 12
Method Naming Guidelines 13
Property Naming Guidelines 13
Event Naming Guidelines 14
Class Member Usage Guidelines 16
Property Usage Guidelines 16
Event Usage Guidelines 25
Method Usage Guidelines 28
Constructor Usage Guidelines 31
Parameter Usage Guidelines 36
Error Raising and Handling Guidelines 37
Array Usage Guidelines 41
Guidelines for Implementing Equals and the Equality Operator (==) 44
Guidelines for Casting Types 45
Common Design Patterns 45
Implementing Finalize and Dispose to Clean Up Unmanaged Resources 45
Implementing the Equals Method 49
Callback Function Usage 54
Time-Out Usage 54




The .NET Framework's managed environment allows developers to improve their programming model to support a wide range of functionality. The goal of the .NET Framework design guidelines is to encourage consistency and predictability in public APIs while enabling Web and cross-language integration. It is strongly recommended that you follow these design guidelines when developing classes and components that extend the .NET Framework. Inconsistent design adversely affects developer productivity. Development tools and add-ins can turn some of these guidelines into de facto prescriptive rules, and reduce the value of nonconforming components. Nonconforming components will function, but not to their full potential.
These guidelines are intended to help class library designers understand the trade-offs between different solutions. There might be situations where good library design requires that you violate these design guidelines. Such cases should be rare, and it is important that you provide a solid justification for your decision. The section provides naming and usage guidelines for types in the .NET Framework as well as guidelines for implementing common design patterns.

Relationship to the Common Type System and the Common Language Specification
The Common Type System is the model that defines the rules the common language runtime follows when declaring, using, and managing types. The common type system establishes a framework that enables cross-language integration, type safety, and high-performance code execution. It is the raw material from which you can build class libraries.
The Common Language Specification (CLS) defines a set of programmatically verifiable rules that governs the interoperation of types authored in different programming languages. Targeting the CLS is an excellent way to ensure cross-language interoperation. Managed class library designers can use the CLS to guarantee that their APIs are callable from a wide range of programming languages. Note that although the CLS encourages good library design, it does not enforce it. For more information on this topic.
You should follow two guiding principles with respect to the CLS when determining which features to include in your class library:
1. Determine whether the feature facilitates the type of API development appropriate to the managed space.
The CLS should be rich enough to provide the ability to write any managed library. However, if you provide multiple ways to perform the same task, you can confuse users of your class library about correct design and usage. For example, providing both safe and unsafe constructs forces users to decide which to use. Therefore, the CLS encourages the correct usage by offering only type-safe constructs.
2. Determine whether it is difficult for a compiler to expose the feature.
All programming languages will require some modification in order to target the runtime and the common type system. However, in order for developers to make a language CLS-compliant, they should not have to create a large amount of additional work. The goal of the CLS is to be as small as possible while offering a rich set of data types and features.

Naming Guidelines
A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library. Widespread use and understanding of these naming guidelines should eliminate many of the most common user questions. This topic provides naming guidelines for the .NET Framework types. For each type, you should also take note of some general rules with respect to capitalization styles, case sensitivity and word choice.
Naming Conventions
Consistency is the key to maintainable code. This statement is most true for naming your projects, source files, and identifiers including Fields, Variables, Properties, Methods, Parameters, Classes, Interfaces, and Namespaces.
General Guidelines
• Always use Camel Case or Pascal Case names.
• Avoid ALL CAPS and all lowercase names. Single lowercase words or letters are acceptable.
• Do not create namespaces, classes, methods, properties, fields, or parameters that vary only by capitalization.
• Do not use names that begin with a numeric character.
• Always choose meaningful and specific names.
• Always err on the side of verbosity not terseness.
• Variables and Properties should describe an entity not the type or size.
• Do not use Hungarian Notation!
• Avoid using abbreviations unless the full name is excessive.
• Avoid abbreviations longer than 5 characters.
• Any Abbreviations must be widely known and accepted.
• Use uppercase for two-letter abbreviations, and Pascal Case for longer abbreviations.
• Do not use C# reserved words as names.
• Avoid naming conflicts with existing .NET Framework namespaces, or types.
• Avoid adding redundant or meaningless prefixes and suffixes to identifiers
• Do not include the parent class name within a property name. “Customer.CustomerName”
• Try to prefix Boolean variables and properties with “Can”, “Is”, “Has”
• Append computational qualifiers to variable names like where “Avg, Count, Sum, Min, Max” appropriate.
• When defining a root namespace, use a Product, Company, or Developer Name as the root.
Code Commenting
• All comments should be written in U.S. English.
• Do not “flowerbox” comment blocks.
• Use inline-comments to explain assumptions, known issues, and algorithm insights.
• Do not use inline-comments to explain obvious code. Well written code is self documenting.
• Only insert inline-comments for Bad Code to say “fix this code” – otherwise, rewrite it!
• Include Task-List keyword flags to enable comment-filtering.
• Incase using C# always apply comment-blocks (///) to Public , protected, and internal
• Always include <summanry> ; comments. Include <Param>;<return> ; and <exception> comment sections where applicable.

Capitalization Styles
Use the following three conventions for capitalizing identifiers.
Pascal case
The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example:
BackColor
Camel case
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example:
backColor
Uppercase
All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters. For example:
System.IO
System.Web.UI
You might also have to capitalize identifiers to maintain compatibility with existing, unmanaged symbol schemes, where all uppercase characters are often used for enumerations and constant values. In general, these symbols should not be visible outside of the assembly that uses them.
The following table summarizes the capitalization rules and provides examples for the different types of identifiers.
Identifier Case Example
Class Pascal AppDomain
Enum type Pascal ErrorLevel
Enum values Pascal FatalError
Event Pascal ValueChange
Exception class Pascal WebException
Note Always ends with the suffix Exception.
Read-only Static field Pascal RedValue
Interface Pascal IDisposable Note Always begins with the prefix I.
Method Pascal ToString
Namespace Pascal System.Drawing
Parameter Camel typeName
Property Pascal BackColor
Protected instance field Camel redValue Note Rarely used. A property is preferable to using a protected instance field.
Public instance field Pascal RedValue Note Rarely used. A property is preferable to using a public instance field.

Case Sensitivity
To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of case sensitivity:
• Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages. Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.
• Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations.
namespace ee.cummings;
namespace Ee.Cummings;
• Do not create a function with parameter names that differ only by case. The following example is incorrect.
void MyFunction(string a, string A)
• Do not create a namespace with type names that differ only by case. In the following example, Point p and POINT p are inappropriate type names because they differ only by case.
System.Windows.Forms.Point p
System.Windows.Forms.POINT p
• Do not create a type with property names that differ only by case. In the following example, int Color and int COLOR are inappropriate property names because they differ only by case.
int Color {get, set}
int COLOR {get, set}
• Do not create a type with method names that differ only by case. In the following example, calculate and Calculate are inappropriate method names because they differ only by case.
void calculate()
void Calculate()

Abbreviations
To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:
• Do not use abbreviations or contractions as parts of identifier names. For example, use GetWindow instead of GetWin.
• Do not use acronyms that are not generally accepted in the computing field.
• Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.
• When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.
• Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.
Avoid using class names that duplicate commonly used .NET Framework namespaces. For example, do not use any of the following names as a class name: System, Collections, Forms, or UI. See the Class Library for a list of .NET Framework namespaces.
In addition, avoid using identifiers that conflict with the following keywords.
AddHandler AddressOf Alias And Ansi
As Assembly Auto Base Boolean
ByRef Byte ByVal Call Case
Catch CBool CByte CChar CDate
CDec CDbl Char CInt Class
CLng CObj Const CShort CSng
CStr CType Date Decimal Declare
Default Delegate Dim Do Double
Each Else ElseIf End Enum
Erase Error Event Exit ExternalSource
False Finalize Finally Float For
Friend Function Get GetType Goto
Handles If Implements Imports In
Inherits Integer Interface Is Let
Lib Like Long Loop Me
Mod Module MustInherit MustOverride MyBase
MyClass Namespace New Next Not
Nothing NotInheritable NotOverridable Object On
Option Optional Or Overloads Overridable
Overrides ParamArray Preserve Private Property
Protected Public RaiseEvent ReadOnly ReDim
Region REM RemoveHandler Resume Return
Select Set Shadows Shared Short
Single Static Step Stop String
Structure Sub SyncLock Then Throw
To True Try TypeOf Unicode
Until volatile When While With
WithEvents WriteOnly Xor eval extends
instanceof package var

Avoiding Type Name Confusion
Different programming languages use different terms to identify the fundamental managed types. Class library designers must avoid using language-specific terminology. Follow the rules described in this section to avoid type name confusion.
Use names that describe a type's meaning rather than names that describe the type. In the rare case that a parameter has no semantic meaning beyond its type, use a generic name. For example, a class that supports writing a variety of data types into a stream might have the following methods.
[Visual Basic]
Sub Write(value As Double);
Sub Write(value As Single);
Sub Write(value As Long);
Sub Write(value As Integer);
Sub Write(value As Short);
[C#]
void Write(double value);
void Write(float value);
void Write(long value);
void Write(int value);
void Write(short value);
Do not create language-specific method names, as in the following example.
[Visual Basic]
Sub Write(doubleValue As Double);
Sub Write(singleValue As Single);
Sub Write(longValue As Long);
Sub Write(integerValue As Integer);
Sub Write(shortValue As Short);
[C#]
void Write(double doubleValue);
void Write(float floatValue);
void Write(long longValue);
void Write(int intValue);
void Write(short shortValue);
In the extremely rare case that it is necessary to create a uniquely named method for each fundamental data type, use a universal type name. The following table lists fundamental data type names and their universal substitutions.


C# type name Visual Basic type name JScript type name Visual C++ type name Ilasm.exe representation Universal type name
sbyte SByte sByte char int8 SByte
byte Byte byte unsigned char unsigned int8 Byte
short Short short short int16 Int16
ushort UInt16 ushort unsigned short unsigned int16 UInt16
int Integer int int int32 Int32
uint UInt32 uint unsigned int unsigned int32 UInt32
long Long long __int64 int64 Int64
ulong UInt64 ulong unsigned __int64 unsigned int64 UInt64
float Single float float float32 Single
double Double double double float64 Double
bool Boolean boolean bool bool Boolean
char Char char wchar_t char Char
string String string String string String
object Object object Object object Object
For example, a class that supports reading a variety of data types from a stream might have the following methods.
[Visual Basic]
ReadDouble()As Double
ReadSingle()As Single
ReadInt64()As Long
ReadInt32()As Integer
ReadInt16()As Short
[C#]
double ReadDouble();
float ReadSingle();
long ReadInt64();
int ReadInt32();
short ReadInt16();
The preceding example is preferable to the following language-specific alternative.
[Visual Basic]
ReadDouble()As Double
ReadSingle()As Single
ReadLong()As Long
ReadInteger()As Integer
ReadShort()As Short
[C#]
double ReadDouble();
float ReadFloat();
long ReadLong();
int ReadInt();
short ReadShort();
Back to top Go down
https://knowledgeshare.forumotion.com
 
Coding Conventions in .net
Back to top 
Page 1 of 1
 Similar topics
-
» Coding Conventions in .net
» Coding Conventions in .net
» Coding Conventions in .net
» Coding Conventions in .net
» Coding Conventions in .net

Permissions in this forum:You cannot reply to topics in this forum
Knowledge Share :: .Net-
Jump to: