ARTICLE

.Net Coding Standards

Posted by Ankur Gupta Articles | VB.NET Articles June 08, 2010
It is very easy to understood your code to another programmer if you write it in a managed manner and follow some standards.
Download Files:
 
Reader Level:

.Net (Vb.Net,C#) Coding Standards.
It is very easy to understood your code to another programmer if you write it in a managed manner and follow some standards.

following are the .Net coding standards (guidelines).

These are the legal Regions to use in a class (in this order):

  •  Local Variables

  •  Events

  • Properties

  • Constructors/Destructors

  • Methods

  • Event Handlers

NOTE: Region titles should be surrounded by one space on either side.
 

Every class member should be separated by a blank line.

Every comment should be preceded by a blank line. Comments should be on their own line and not included to the right of code, except in the case of one or two word notes (e.g., noting a default value in place of initialization).

Comments should be complete sentences starting with a capitalized word and ending with a period. Grammar IS important.

Insert one space between the comment delimiter (') and the comment text.

 

All class members should include summary XML comments.
 

All methods should additionally include param XML comments for every parameter and should match the order that they are listed in the method signature.
 

All functions should additionally include returns XML comments.
 

Properties should be documented with summary and value XML comments, but the returns is redundant and should not be used.
 

Properties summary comments should begin with "Gets or sets" as appropriate to its permission modifier.  (i.e., the Public usability of Get and Set blocks)

''' <summary>

''' Gets or sets the text associated with this control.

''' </summary>

''' <value>The text associated with this control.</value>

Public Property Text() As String

''' <summary>

''' Retrieves a value indicating whether the specified control is a

''' child of the control.

''' </summary>

''' <param name="ctl">The System.Windows.Forms.Control to

''' evaluate.</param>

''' <returns>true if the specified control is a child of the control;

''' otherwise, false.</returns>

Public Function Contains(ByVal ctl As System.Windows.Forms.Control) _

        As Boolean
 

Avoid the use of implementation details in XML comments. Comments should not reference data types, other methods, etc.

Remarks XML comments are optional, but may be used to describe additional information. This may include implementation details.

Naming Conventions

 

Begin each separate word in a name with a capital letter (Pascal case), as in FindLastRecord and RedrawMyForm.

Begin function and method names with a verb, as in InitNameArray or CloseDialog.

Begin class, structure, module, and property names with a noun, as in EmployeeName or CarAccessory.

Begin interface names with the prefix "I", followed by a noun or a noun phrase, like IComponent, or with an adjective describing the interface's behavior, like IPersistable. Do not use the underscore, and use abbreviations sparingly, because abbreviations can cause confusion.

Begin event handler names with a noun describing the type of event followed by the "EventHandler" suffix, as in "MouseEventHandler".

In names of event argument classes, include the "EventArgs" suffix.

If an event has a concept of "before" or "after," use a prefix in present or past tense, as in "ControlAdd" or "ControlAdded".

For long or frequently used terms, use abbreviations to keep name lengths reasonable, for example, "HTML", instead of "Hypertext Markup Language". In general, variable names greater than 32 characters are difficult to read on a monitor set to a low resolution. Also, make sure your abbreviations are consistent throughout the entire application. Randomly switching in a project between "HTML" and "Hypertext Markup Language" can lead to confusion.

Avoid using names in an inner scope that are the same as names in an outer scope. Errors can result if the wrong variable is accessed. If a conflict occurs between a variable and the keyword of the same name, you must identify the keyword by preceding it with the appropriate type library. For example, if you have a variable called Date, you can use the intrinsic Date function only by calling System.DateTime.Date.

Private fields should be prefixed with 'm' to represent class member variables.

Const declarations should use Pascal case.

Enumerations should use Pascal case. The name should be singular unless you are using bitwise flags.

Use descriptive names for everything. Do not abbreviate unless it's a very common abbreviation (e.g. ID). Spelling IS important.

User Interface

Windows Forms
 

All usable controls should be checked for correct TabStop and Anchoring.

Exception Handling

 

Only catch specific exceptions (i.e. NullReferenceException, SQLException, etc.).
 

Exception to the above rule is using ADODB connections, which only throw base System.Exception types.
 

Only use a Try...Catch when you can add something relevant to the exception being caught.
 

Close and dispose of local managed resources within the Finally block.
 

Dim myFile As System.IO.FileStream = Nothing

Try

    myFile = New System.IO.FileStream("myFile.dat", IO.FileMode.Open)

    ' File processing code block here

Catch ex As System.IO.IOException

    ' Error handling code block here

Finally

    If (myFile IsNot Nothing) Then

        myFile.Close()

    End If

End Try

The Using statement combines a Try...Catch statement with a call to the Dispose method and simplifies the code. If you are using a Try...Catch statement and the only code in the Finally block is a call to the Dispose method, use the Using statement instead.

 

Using myDlgFrm As New MyCustomDialogForm()

    ' Any setup code for myCustomDlgForm

    If (myDlgFrm.ShowDialog() = Windows.Forms.DialogResult.OK) Then

        ' Any code to handle values declared on the dialog

    End If

End Using


Other .NET

Be strict in the use of access modifiers. Start with private access and allow more access only as needed.
 

Option Explicit and Option Strict should always be On.
 

Do not use Dim to declare class fields.
 

Avoid the use of protected fields. Use protected properties instead.
 

One class per file (except for nested classes).
 

Do not use optional parameters.
 

Do not use single-line if statements.
 

Use Me. when referring to instanced members.
 

Use the IsNot keyword in preference to Not...Is Nothing.

Use AndAlso instead of And and OrElse instead of Or when you perform comparisons.
 

Use Handles rather than AddHandler (except for dynamically generated controls).
 

Use AddressOf, and do not instantiate the delegate explicitly.
 

Use My features in preference to the .NET Framework class library or the Visual Basic run-time library. For more information, see Objects (Visual Basic).
 

Separate large/complex/frequently used code logic into separate functions and possibly separate classes.  This will help with code readability, maintainability, and reusability.  This applies to UI components as well.
 

Explicitly release external resources (i.e. streams, connections, etc.) when you are finished with them.

String Data Type

     

Use String.Compare when comparing strings, but use String.Length when checking for empty strings.
 

Use & to concatenate strings.
 

For appending strings in loops use the StringBuilder object.

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Team Foundation Server Hosting
Become a Sponsor