Sei sulla pagina 1di 26

Standard

VB.NET Coding Convention

Code 09he-HD/PM/HDCV/FSOFT

Version 1/1

Effective date 10/Jun/2013


Standard_VB.Net Coding Convention v1/1

TABLE OF CONTENTS

Table of Contents .............................................................................................................. 2

1. INTRODUCTION............................................................................................. 4

1.1. Purpose ................................................................................................................... 4


1.2. Application scope ..................................................................................................... 4
1.3. Related documents .................................................................................................. 4

2. NAMING CONVENTION .................................................................................. 5

2.1. Capitalization Styles ................................................................................................. 5


2.2. Abbreviations ........................................................................................................... 6
2.3. Assemblies and DLLs Naming Guidelines ................................................................ 7
2.4. Namespace Naming Guidelines................................................................................ 7
2.5. Class Naming Guideline ........................................................................................... 8
2.6. ADO.NET Naming class variable .............................................................................. 9
2.7. Interface Naming Guideline ...................................................................................... 9
2.8. Attribute Naming Guideline ..................................................................................... 10
2.9. Enumeration Type Naming Guideline ..................................................................... 10
2.10. Static Field Naming Guideline................................................................................. 10
2.11. Parameter Naming Guideline.................................................................................. 11
2.12. Method Naming Guideline ...................................................................................... 11
2.13. Property Naming Guideline..................................................................................... 11
2.14. Variable Naming Guideline ..................................................................................... 13
2.15. Event Naming Guideline ......................................................................................... 13
2.16. Control Naming Guideline....................................................................................... 14
2.17. Constant Naming Guideline .................................................................................... 16
2.18. Resources Naming Guidelines ............................................................................... 16
2.19. Code Comments .................................................................................................... 17

3. CODE FORMATS ......................................................................................... 19

3.1. General coding-format standard ............................................................................. 19


3.2. Stored-Procedures calling standard ........................................................................ 20
3.3. Program Structure .................................................................................................. 21
3.4. String Data Type .................................................................................................... 21
3.5. Relaxed Delegates in Event Handlers..................................................................... 21

09he-HD/PM/HDCV/FSOFT 2/26
Standard_VB.Net Coding Convention v1/1

3.6. Unsigned Data Type............................................................................................... 21


3.7. Arrays .................................................................................................................... 21
3.8. Use the With Keyword ............................................................................................ 22
3.9. Use the IsNot Keyword ........................................................................................... 22
3.10. New Keyword ......................................................................................................... 22
3.11. Event Handling ....................................................................................................... 23
3.12. Using Shared Members .......................................................................................... 23
3.13. Use XML Literals .................................................................................................... 23
3.14. LINQ Queries ......................................................................................................... 24
3.15. Miscellaneous ........................................................................................................ 25

09he-HD/PM/HDCV/FSOFT 3/26
Standard_VB.Net Coding Convention v1/1

1. INTRODUCTION

1.1. Purpose

Code conventions are important to programmers for a number of reasons:


 80% of the lifetime cost of a piece of software goes to maintenance.
 Hardly any software is maintained for its whole life by the original author.
 Code conventions improve the readability of the software, allowing engineers to
understand new code more quickly and thoroughly.
If you ship your source code as a product, you need to make sure it is as well packaged and
clean as any other product you create.

1.2. Application scope

All projects developed in VB.NET will be under scope of this standard.

1.3. Related documents

No. Code Name of documents

1 04e-QT/PM/HDCV/FSOFT Process_Coding

2 MS Visual Basic DotNET Programmer Guide

09he-HD/PM/HDCV/FSOFT 4/26
Standard_VB.Net Coding Convention v1/1

2. NAMING CONVENTION

Naming conventions make programs more understandable by making them easier to read.
This section lists the convention to be used in naming. You do not have to change the names
of objects in auto-generated code so that they respect this convention.

2.1. Capitalization Styles

We will use the three following 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 Value Pascal FatalError

Event Pascal ValueChange

Exception class Pascal WebException

Note: Always ends with the suffix


Exception

09he-HD/PM/HDCV/FSOFT 5/26
Standard_VB.Net Coding Convention v1/1

Identifier Case Example

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 Camel redValue


field
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

Languages that can run on the CLR are not required to support case-sensitivity, although
some do. Even if your language supports it, other languages that might access your
framework do not. Any APIs that are externally accessible, therefore, cannot rely on case
alone to distinguish between two names in the same context.

DO NOT assume that all programming languages are case sensitive. They are not. Names
cannot differ by case alone.

2.2. 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

09he-HD/PM/HDCV/FSOFT 6/26
Standard_VB.Net Coding Convention v1/1

abbreviations, use Camel Case for abbreviations that consist of more than two
characters, even if this contradicts the standard abbreviation of the word.

2.3. Assemblies and DLLs Naming Guidelines

An assembly is the unit of deployment and identity for managed code programs. Although
assemblies can span one or more files, typically an assembly maps one-to-one with a DLL.
Therefore, this section describes only DLL naming conventions, which then can be mapped to
assembly naming conventions.
 DO choose names for your assembly DLLs that suggest large chunks of functionality,
such as System.Data.

Assembly and DLL names don’t have to correspond to namespace names, but it is
reasonable to follow the namespace name when naming assemblies. A good rule of
thumb is to name the DLL based on the common prefix of the assemblies contained in
the assembly. For example, an assembly with two
namespaces, MyCompany.MyTechnology.FirstFeature and MyCompany.MyTechnology
.SecondFeature, could be calledMyCompany.MyTechnology.dll.
 CONSIDER naming DLLs according to the following pattern:

<Company>.<Component>.dll
where <Component> contains one or more dot-separated clauses. For example:
Litware.Controls.dll.

2.4. Namespace Naming Guidelines.

The general rule for naming namespaces is to use the company name followed by the
technology name and optionally the feature and design as follows.
CompanyName.Technology[.Feature][.Design]

For example:
Microsoft.Media
Microsoft.Media.Design

Prefixing namespace names with a company name or other well-established brand avoids the
possibility of two published namespaces having the same name. For example,
Microsoft.Office is an appropriate prefix for the Office Automation Classes provided by
Microsoft.
Use a stable, recognized technology name at the second level of a hierarchical name. Use
organizational hierarchies as the basis for namespace hierarchies. Name a namespace that
contains types that provide design-time functionality for a base namespace with the .Design
suffix. For example, the System.Windows.Forms.Design Namespace contains designers
and related classes used to design System.Windows.Forms based applications.

A nested namespace should have a dependency on types in the containing namespace. For
example, the classes in the System.Web.UI.Design depend on the classes in
System.Web.UI. However, the classes in System.Web.UI do not depend on the classes in

09he-HD/PM/HDCV/FSOFT 7/26
Standard_VB.Net Coding Convention v1/1

System.Web.UI.Design.

You should use Pascal case for namespaces, and separate logical components with periods,
as in Microsoft.Office.PowerPoint. If your brand employs nontraditional casing, follow
the casing defined by your brand, even if it deviates from the prescribed Pascal case. For
example, the namespaces NeXT.WebObjects and ee.cummings illustrate appropriate
deviations from the Pascal case rule.
Use plural namespace names if it is semantically appropriate. For example, use
System.Collections rather than System.Collection. Exceptions to this rule are brand
names and abbreviations. For example, use System.IO rather than System.IOs.
Do not use the same name for a namespace and a class. For example, do not provide both a
Debug namespace and a Debug class.
Finally, note that a namespace name does not have to parallel an assembly name. For
example, if you name an assembly MyCompany.MyTechnology.dll, it does not have to
contain a MyCompany.MyTechnology namespace.

2.5. Class Naming Guideline

The following rules outline the guidelines for naming classes:


 Use a noun or noun phrase to name a class.

 Use Pascal case.

 Use abbreviations sparingly.

 Do not use a type prefix, such as C for class, on a class name. For example, use the
class name FileStream rather than CFileStream.

 Do not use the underscore character (_).

 Occasionally, it is necessary to provide a class name that begins with the letter I, even
though the class is not an interface. This is appropriate as long as I is the first letter of
an entire word that is a part of the class name. For example, the class name
IdentityStore is appropriate.

 Where appropriate, use a compound word to name a derived class. The second part of
the derived class's name should be the name of the base class. For example,
ApplicationException is an appropriate name for a class derived from a class
named Exception, because ApplicationException is a kind of Exception. Use
reasonable judgment in applying this rule. For example, Button is an appropriate name
for a class derived from Control. Although a button is a kind of control, making
Control a part of the class name would lengthen the name unnecessarily.

The following are examples of correctly named classes:


Public Class FileStream
Public Class Button
Public Class String

09he-HD/PM/HDCV/FSOFT 8/26
Standard_VB.Net Coding Convention v1/1

2.6. ADO.NET Naming class variable

 Express the name of DataTable variables in the plural form. For example, use
Employees rather than Employee.

 Do not repeat the table name in the column name. If the DataTable name is
Employee, LastName is preferred over EmployeeLastName. The exception is for ID
fields contained in multiple tables, so that that Employees table may contain an
EmployeeID field.

 Do not incorporate the data type in the name of a column. If the data type is later
changed, and the column name is not changed, the column name would be misleading.
For example, LastName is preferred over stringLastName.

2.7. Interface Naming Guideline

The following rules outline the naming guidelines for interfaces:


 Name interfaces with nouns or noun phrases, or adjectives that describe behavior. For
example, the interface name IComponent uses a descriptive noun. The interface name
ICustomAttributeProvider uses a noun phrase. The name IPersistable uses
an adjective.

 Use Pascal case.

 Use abbreviations sparingly.

 Prefix interface names with the letter I, to indicate that the type is an interface.

 Use similar names when you define a class/interface pair where the class is a standard
implementation of the interface. The names should differ only by the letter I prefix on
the interface name.

 Do not use the underscore character (_).

 The following are examples of correctly named interfaces.


 Public Interface IServiceProvider
 Public Interface IFormatable

 The following code example illustrates how to define the interface IComponent and its
standard implementation, the class Component.
Public Interface IComponent
‘Implementation code goes here
End Interface

Public Class Component


Implements IComponent
‘Implementation code goes here
End Class

09he-HD/PM/HDCV/FSOFT 9/26
Standard_VB.Net Coding Convention v1/1

2.8. Attribute Naming Guideline

You should always add the suffix Attribute to custom attribute classes. The following is an
example of a correctly named attribute class.
Public Class ObsoleteAttribute

2.9. Enumeration Type Naming Guideline

The enumeration (Enum) value type inherits from the Enum Class. The following rules outline
the naming guidelines for enumerations:
 Use Pascal case for Enum types and value names.

 Use abbreviations sparingly.

 Do not use an Enum, Flag, Flags suffixes on Enum type names.

 Use a singular name for most Enum types, but use a plural name for Enum types that
are bit fields.

 Always add the FlagsAttribute to a bit field Enum type.

Example of correctly named enum:


Public Enum InterfaceColor
MistyRose = &HE1E4FF&
SlateGray = &H908070&
DodgerBlue = &HFF901E&
DeepSkyBlue = &HFFBF00&
SpringGreen = &H7FFF00&
ForestGreen = &H228B22&
Goldenrod = &H20A5DA&
Firebrick = &H2222B2&
End Enum

2.10. Static Field Naming Guideline

The following rules outline the naming guidelines for static fields:
 Use nouns, noun phrases, or adjectives to name static fields.

 Use Pascal case.

 Do not use a Hungarian notation prefix on static field names.

 It is recommended that you use static properties instead of public static fields whenever
possible.

Example of correctly named static field:

Private Shared referenceCount As Integer

09he-HD/PM/HDCV/FSOFT 10/26
Standard_VB.Net Coding Convention v1/1

2.11. Parameter Naming Guideline

It is important to carefully follow these parameter naming guidelines because visual design
tools that provide context sensitive help and class browsing functionality display method
parameter names to users in the designer. The following rules outline the naming guidelines
for parameters:
 Use camel case for parameter names.

 Use descriptive parameter names. Parameter names should be descriptive enough that
the name of the parameter and its type can be used to determine its meaning in most
scenarios. For example, visual design tools that provide context sensitive help display
method parameters to the developer as they type. The parameter names should be
descriptive enough in this scenario to allow the developer to supply the correct
parameters.
 Use names that describe a parameter's meaning rather than names that describe a
parameter's type. Development tools should provide meaningful information about a
parameter's type. Therefore, a parameter's name can be put to better use by describing
meaning. Use type-based parameter names sparingly and only where it is appropriate.
 Do not use reserved parameters. Reserved parameters are private parameters that
might be exposed in a future version if they are needed. Instead, if more data is needed
in a future version of your class library, add a new overload for a method.
 Do not prefix parameter names with Hungarian type notation.

The following are examples of correctly named parameters.


GetType(typeName As String) As Type
Format(format As String, args() As object) As String

2.12. Method Naming Guideline

The following rules outline the naming guidelines for methods:


 Use verbs or verb phrases to name methods.

 Use Pascal case.

The following are examples of correctly named methods.


RemoveAll()
GetCharArray()
Invoke()

2.13. Property Naming Guideline

The following rules outline the naming guidelines for properties:


 Use a noun, noun phrase, or adjective to name properties.

 Use Pascal case.

 Do not use Hungarian notation.

09he-HD/PM/HDCV/FSOFT 11/26
Standard_VB.Net Coding Convention v1/1

 DO NOT have properties that match the name of "Get" methods as in the following
example

public string TextWriter { get {...} set {...} }


public string GetTextWriter(int value) { ... }

 CONSIDER giving a property the same name as its type, as in the example later in this
topic.

The following code example illustrates correct property naming.


Public Class SampleClass
Public Property BackColor As Color
‘ Code for Get and Set accessors go here
End Property
End Class
The following code example illustrates providing a property with the same name as a type.
Public Enum Color
‘Insert code for Enum here
End Enum

Public Class Control


Public Property Color as Color
Get
‘Insert code here
End Get
Set
‘Insert code here
End Set
End Property
End Class
The following code example is incorrect because the property Color is of type Integer.
Public Enum Color
‘Insert code for Enum here
End Enum
Public Class Control
Public Property Color As Integer
Get
‘Insert code here
End Get
Set
‘Insert code here
End Set
End Property
End Class
In the incorrect example, it is not possible to refer to the members of the Color enumeration.
Color.Xxx will be interpreted as accessing a member that first gets the value of the Color
property (type Integer in Visual Basic or type int in C#) and then accesses a member of that
value (which would have to be an instance member of System.Int32).

09he-HD/PM/HDCV/FSOFT 12/26
Standard_VB.Net Coding Convention v1/1

2.14. Variable Naming Guideline

The following rules outline the naming guidelines for properties:


 Use a noun or noun phrase to name properties.

 Use Camel case. For primitive type variables, the prefix for variables will be lower-case.

 Do not use Hungarian notation prefixes.

2.15. Event Naming Guideline

The following rules outline the naming guidelines for events:


 Use Pascal case.

 Do not use Hungarian notation.

 Use an EventHandler suffix on event handler names.

 Specify two parameters named sender and e. The sender parameter represents the
object that raised the event. The sender parameter is always of type object, even if it is
possible to use a more specific type. The state associated with the event is
encapsulated in an instance of an event class named e. Use an appropriate and specific
event class for the e parameter type.
 Name an event argument class with the EventArgs suffix.

 Consider naming events with a verb. For example, correctly named event names include
Clicked, Painting, and DroppedDown.

 Use a gerund (the "ing" form of a verb) to create an event name that expresses the
concept of pre-event, and a past-tense verb to represent post-event. For example, a
Close event that can be canceled should have a Closing event and a Closed event.
Do not use the BeforeXxx/AfterXxx naming pattern.

 Do not use a prefix or suffix on the event declaration on the type. For example, use
Close instead of OnClose.

 In general, you should provide a protected method called OnXxx on types with events
that can be overridden in a derived class. This method should only have the event
parameter e, because the sender is always the instance of the type.

The following example illustrates an event handler with an appropriate name and parameters.
Public Delegate Sub MouseEventHandler(sender As Object, e As
MouseEventArgs)

09he-HD/PM/HDCV/FSOFT 13/26
Standard_VB.Net Coding Convention v1/1

The following example illustrates a correctly named event argument class.


Public Class MouseEventArgs
Inherits EventArgs
Dim x As Integer
Dim y As Integer
Public Sub New MouseEventArgs(x As Integer, y As
Integer)
me.x = x
me.y = y
End Sub
Public Property X As Integer
Get
Return x
End Get
End Property
Public Property Y As Integer
Get
Return y
End Get
End Property
End Class

2.16. Control Naming Guideline

Control type Prefix Example

3D Panel pnl pnlGroup

ADO Data ado adoBiblio


Animated button ani aniMailBox

Check box chk chkReadOnly

Combo box, drop-down list box cbo cboEnglish


Command button cmd cmdExit

Common dialog dlg dlgFileOpen

Communications com comFax


Control (used within procedures ctr ctrCurrent
when the specific type is unknown)

Data dat datBiblio

Data-bound combo box cbo cboLanguage


Data-bound grid grd grdQueryResult

Data-bound list box lst lstJobType


Data repeater drp drpLocation

Date picker dtp dtpPublished

Directory list box dir dirSource

09he-HD/PM/HDCV/FSOFT 14/26
Standard_VB.Net Coding Convention v1/1

Control type Prefix Example

Drive list box drv drvTarget

File list box fil filSource

Flat scroll bar fsb fsbMove

Form frm frmEntry

Frame fra fraLanguage

Gauge gau gauStatus

Graph gra graRevenue

Grid grd grdPrices

Hierarchical flexgrid flex flexOrders

Horizontal scroll bar hsb hsbVolume

Image img imgIcon

Image combo Imgcbo imgcboProduct

ImageList ils ilsAllIcons

Label lbl lblHelpMessage

Line lin linVertical

List box lst lstPolicyCodes

ListView lvw lvwHeadings

Menu mnu mnuFileOpen

Month view mvw mvwPeriod

MS Chart ch chSalesbyRegion

MS Flex grid msg msgClients

MS Tab mst mstFirst

OLE container ole oleWorksheet

Option button opt optGender

Picture box pic picVGA

Picture clip clp clpToolbar

ProgressBar prg prgLoadFile

Remote Data rd rdTitles

RichTextBox rtf rtfReport

Shape shp shpCircle

09he-HD/PM/HDCV/FSOFT 15/26
Standard_VB.Net Coding Convention v1/1

Control type Prefix Example

Slider sld sldScale

Spin spn spnPages

StatusBar sta staDateTime

SysInfo sys sysMonitor

TabStrip tab tabOptions

Text box txt txtLastName

Timer tmr tmrAlarm

Toolbar tlb tlbActions

TreeView tre treOrganization

UpDown upd updDirection

Vertical scroll bar vsb vsbRate

2.17. Constant Naming Guideline

To clearly distinguish constants from other elements, use all uppercase when naming them.
An underscore can be used to separate terms when necessary.
Example:

Const MIN_QUAL = 25

2.18. Resources Naming Guidelines

Because localizable resources can be referenced via certain objects as if they were properties,
the naming guidelines for resources are similar to property guidelines.
 DO use PascalCasing in resource keys.

 DO provide descriptive rather than short identifiers.

 DO NOT use language-specific keywords of the main CLR languages.

 DO use only alphanumeric characters and underscores in naming resources.

 DO use the following naming convention for exception message resources.

The resource identifier should be the exception type name plus a short identifier of the
exception:
ArgumentExceptionIllegalCharacters
ArgumentExceptionInvalidName
ArgumentExceptionFileNameIsMalformed

09he-HD/PM/HDCV/FSOFT 16/26
Standard_VB.Net Coding Convention v1/1

2.19. Code Comments

The following rules are applied when commenting your code:


 Comment each type, each non-public type member, and each region declaration.

Comments should be used to give overviews of code and provide additional information
that is not readily available in the code itself. Comments should contain only information
that is relevant to reading and understanding the program. For example, information
about how the corresponding package is built or in what directory it resides should not
be included as a comment.
Block comments will be placed on top of the commented code. For Class comment we
have the following block:

'----------------------------------------------------------------
' Namespace :
' Class :
'
' Description:
'
'----------------------------------------------------------------

Comments for Functions will be as follows:

'----------------------------------------------------------------
' Function GetCustomerByEmail:
' Retrieve a customer given the customer's email and password.
' Returns:
' The customer or Nothing
' Parameters:
' [in] emailAddress: Customer's email address
' [in] password: Customer's account password
' Throws:
' PreConditionException
' PreConditions:
' emailAddress or password is blank
'----------------------------------------------------------------
Public Function GetCustomerByEmail(ByVal emailAddress As String,
ByVal password As String) As CustomerData

 Use end-line comments only on variable declaration lines. End-line comments are
comments that follow code on a single line.

Dim dataSet As CustomerData ' used manipulate CustomerData

 For on-fly commenting, insert the comment sentence(s) between two blank commenting
lines. The following code illustrates on-fly commenting.

‘ This calls something method.

anObject.SomethingMethod
 Do not create formatted blocks of asterisks that surround comments.

09he-HD/PM/HDCV/FSOFT 17/26
Standard_VB.Net Coding Convention v1/1

 Separate comments from comment delimiters (apostrophe) with one space.

 Begin the comment text with an uppercase letter.

 End the comment with a period.

 If the comment starts with a verb, it should be in the imperative (Loop, Add, Write, and
so forth).

 Explain the code; do not repeat it.

09he-HD/PM/HDCV/FSOFT 18/26
Standard_VB.Net Coding Convention v1/1

3. CODE FORMATS

3.1. General coding-format standard

 Insert tabs as spaces, and use smart indenting with four-space indents.

 Use the "Pretty Listing" feature (in the Tools Options dialog box) of Visual Studio .NET
to format the code. Use the default settings for the pretty listing feature (Smart indenting,
Tab 4, Indent 4, Insert spaces).

 One declaration per line is recommended since it encourages commenting. In other


words,

Dim intRows As Integer ' indentation level


Dim intSize As Integer ' size of table

Is preferred over

Dim intRow As Integer, intSize As Integer

 Use the short method for instantiating classes.

' Preferred
Dim Employees as New Collection()
' Not Preferred
Dim Employees as Collection = New Collection()

 Indent continuation lines one tab stop.

 Write only one statement per line.

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

 Define only one type (class, enum, interface, and so forth) in each file

 Maximum number of characters in one line is 80 chars. If one statement is longer than
the MAX, we must follow the rules for line break below:

 Break after open parenthesis or commas or equal sign

 Break before operation

 Must insert one more tab before or not


Public Delegate Sub MouseEventHandler(sender As Object, e As
MouseEventArgs)

Should be:

Public Delegate Sub MouseEventHandler(sender As Object,


e As MouseEventArgs)

09he-HD/PM/HDCV/FSOFT 19/26
Standard_VB.Net Coding Convention v1/1

3.2. Stored-Procedures calling standard

The system will mainly manipulate with the Database through calling stored-procedures. A
method calling stored procedures will contain 3 parts:
 Create connection and SQL command. Set the stored procedure to be run.

 Create Parameter and pass parameters to the command.

 Execute the command to get the DataSet

The following code illustrates standard function calling a stored procedure and returning a
dataset.
Public Function CategoryClassList(ByVal CatMasterID As
Integer, ByVal CatClassID As Integer) As DataSet

‘ Create connection and SQL command. Set the stored
‘ procedure to be run.

Dim objConn = New SqlConnection(Global.ConnectionString)
Dim objCommand = New SqlCommand("s_CategoryClassList",
objConn)
objCommand.CommandType = CommandType.StoredProcedure
Dim da = New SqlDataAdapter(objCommand)
Dim ds As New DataSet()

‘ Create Parameter and pass parameters to the command

Dim param As SqlParameter

param = objCommand.Parameters.Add("@CatMasterID",
SqlDbType.Int)
param.Direction = ParameterDirection.Input
param.Value = CatMasterID

param = objCommand.Parameters.Add("@CatClassID",
SqlDbType.Int)
param.Direction = ParameterDirection.Input
param.Value = CatClassID

‘ Execute the command to get the DataSet

Try
objConn.Open()
da.Fill(ds)
objConn.Close()
Return ds
Catch
Dim strError As String = Err.Description
Return Nothing
End Try

End Function

09he-HD/PM/HDCV/FSOFT 20/26
Standard_VB.Net Coding Convention v1/1

3.3. Program Structure

When you use the Main method, use the default construct for new console applications, and
use My for command-line arguments.
Sub Main()
For Each argument As String In
My.Application.CommandLineArgs
' Add code here to use the string variable.
Next
End Sub

3.4. String Data Type

 To concatenate strings, use an ampersand (&).

MsgBox("hello" & vbCrLf & "goodbye")

 To append strings in loops, use the StringBuilder object.


Dim longString As New System.Text.StringBuilder
For count As Integer = 1 To 1000
longString.Append(count)
Next

3.5. Relaxed Delegates in Event Handlers

Do not explicitly qualify the arguments (Object and EventArgs) to event handlers. If you are
not using the event arguments that are passed to an event (for example, sender as Object, e
as EventArgs), use relaxed delegates, and leave out the event arguments in your code:

Public Sub Form1_Load() Handles Form1.Load


End Sub

3.6. Unsigned Data Type

Use Integer rather than unsigned types, except where they are necessary.

3.7. Arrays

 Use the short syntax when you initialize arrays on the declaration line. For example, use
the following syntax.
Dim letters1 As String() = {"a", "b", "c"}

Do not use the following syntax.


Dim letters2() As String = New String() {"a", "b", "c"}

09he-HD/PM/HDCV/FSOFT 21/26
Standard_VB.Net Coding Convention v1/1

 Put the array designator on the type, not on the variable. For example, use the following
syntax:

Dim letters4 As String() = {"a", "b", "c"}

Do not use the following syntax:

Dim letters3() As String = {"a", "b", "c"}

 Use the { } syntax when you declare and initialize arrays of basic data types. For example,
use the following syntax:

Dim letters5() As String = {"a", "b", "c"}

Do not use the following syntax:


Dim letters6(2) As String
letters6(0) = "a"
letters6(1) = "b"
letters6(2) = "c"

3.8. Use the With Keyword

When you make a series of calls to one object, consider using the With keyword:
With orderLog
.Log = "Application"
.Source = "Application Name"
.MachineName = "Computer Name"
End With

3.9. Use the IsNot Keyword

Use the IsNot keyword instead of Not...Is Nothing.

3.10. New Keyword

 Use short instantiation. For example, use the following syntax:

Dim employees As New List(Of String)

The preceding line is equivalent to this:

Dim employees2 As List(Of String) = New List(Of String)

09he-HD/PM/HDCV/FSOFT 22/26
Standard_VB.Net Coding Convention v1/1

 Use object initializers for new objects instead of the parameterless constructor:

Dim orderLog As New EventLog With {


.Log = "Application",
.Source = "Application Name",
.MachineName = "Computer Name"}

3.11. Event Handling

 Use Handles rather than AddHandler:

Private Sub ToolStripMenuItem1_Click() Handles


ToolStripMenuItem1.Click
End Sub

 Use AddressOf, and do not instantiate the delegate explicitly:

Dim closeItem As New ToolStripMenuItem(


"Close", Nothing, AddressOf ToolStripMenuItem1_Click)
Me.MainMenuStrip.Items.Add(closeItem)

 When you define an event, use the short syntax, and let the compiler define the delegate:

Public Event SampleEvent As EventHandler(Of SampleEventArgs)


' or
Public Event SampleEvent(ByVal source As Object,
ByVal e As SampleEventArgs)

 Do not verify whether an event is Nothing (null) before you call


the RaiseEvent method. RaiseEvent checks for Nothing before it raises the event.

3.12. Using Shared Members

Call Shared members by using the class name, not from an instance variable.

3.13. Use XML Literals

XML literals simplify the most common tasks that you encounter when you work with XML (for
example, load, query, and transform). When you develop with XML, follow these guidelines:
 Use XML literals to create XML documents and fragments instead of calling XML APIs
directly.
 Import XML namespaces at the file or project level to take advantage of the performance
optimizations for XML literals.
 Use the XML axis properties to access elements and attributes in an XML document.

09he-HD/PM/HDCV/FSOFT 23/26
Standard_VB.Net Coding Convention v1/1

 Use embedded expressions to include values and to create XML from existing values
instead of using API calls such as the Addmethod:
Private Function GetHtmlDocument(
ByVal items As IEnumerable(Of XElement)) As String

Dim htmlDoc = <html>


<body>
<table border="0" cellspacing="2">
<%=
From item In items
Select <tr>
<td style="width:480">
<%= item.<title>.Value %>
</td>
<td><%=
item.<pubDate>.Value %></td>
</tr>
%>
</table>
</body>
</html>

Return htmlDoc.ToString()
End Function

3.14. LINQ Queries

 Use meaningful names for query variables:

Dim seattleCustomers = From cust In customers


Where cust.City = "Seattle"

 Provide names for elements in a query to make sure that property names of anonymous
types are correctly capitalized using Pascal casing:
Dim customerOrders = From customer In customers
Join order In orders
On customer.CustomerID Equals
order.CustomerID
Select Customer = customer, Order =
order

 Rename properties when the property names in the result would be ambiguous. For
example, if your query returns a customer name and an order ID, rename them instead of
leaving them as Name and ID in the result:

09he-HD/PM/HDCV/FSOFT 24/26
Standard_VB.Net Coding Convention v1/1

Dim customerOrders2 = From cust In customers


Join ord In orders
On cust.CustomerID Equals
ord.CustomerID
Select CustomerName = cust.Name,
OrderID = ord.ID

 Use type inference in the declaration of query variables and range variables:

Dim customerList = From cust In customers

 Align query clauses under the From statement:

Dim newyorkCustomers = From cust In customers


Where cust.City = "New York"
Select cust.LastName, cust.CompanyName

 Use Where clauses before other query clauses so that later query clauses operate on the
filtered set of data:

Dim newyorkCustomers2 = From cust In customers


Where cust.City = "New York"
Order By cust.LastName

 Use the Join clause to explicitly define a join operation instead of using the Where clause
to implicitly define a join operation:

Dim customerList2 = From cust In customers


Join order In orders
On cust.CustomerID Equals
order.CustomerID
Select cust, order

3.15. Miscellaneous

 Use Visual Basic runtime methods rather than .NET Framework objects.
 Do not explicitly instantiate a delegate in the AddHandler statement.
 Use the Declare statement rather than the DllImport attribute to access native APIs.
 Avoid use of single-line If statement.
 Declare the array length with the variable name.

09he-HD/PM/HDCV/FSOFT 25/26
Standard_VB.Net Coding Convention v1/1

' Preferred.
Dim Buttons(4) As Button

' Not preferred.


Dim Buttons() As Button = New Button() {}

 Use Try…Catch rather than "On Error".

 Use CStr() instead of Str().

 Use CInt() instead of Int().

 Use Option Strict On, either as a project setting or as a statement in each file.

 Use Option Explicit On, either as a project setting or as a statement in each file.

 Use the complete class name when applying an attribute.


 Use shared methods in classes rather than global methods in modules.
 Do not use type characters ($, %, and so on).
Do not use Call.

Approver Reviewer Creator

Nguyen Quang Hoa Le Hoang Viet Truong Hong Thi

09he-HD/PM/HDCV/FSOFT 26/26

Potrebbero piacerti anche