Share via


Visual Basic Coding Conventions 

These guidelines are used by Microsoft to develop samples and documentation. The Visual Basic Language Specification does not define a coding standard.

  • Coding conventions create a consistent look to the code, so that readers can focus on content, not layout.

  • Conventions let the readers understand the code more quickly, because it allows them to make assumptions based on previous experience.

  • Conventions make copying, changing, and maintaining the code easier.

  • Conventions demonstrate Visual Basic "best practices."

Discussion

Naming Conventions

  • Naming guidelines are covered in Design Guidelines for Developing Class Libraries.

  • You do not have to change the name of objects created by the Visual Studio designer tools to make them fit the guidelines.

  • Use namespace qualifications rather than adding Imports statements. If a namespace is imported by default in a project, you do not have to fully qualify the code because it will run unqualified with Intellisense when copied and pasted. When you are breaking long lines of code to make them easier to read, qualified names can be broken after the "." For example:

    Dim collection As System.Diagnostics. _
           InstanceDataCollectionCollection
    
  • Do not use "My" or "my" as part of a variable name. This creates confusion with the My objects.

Layout Conventions

Good layout uses formatting to emphasize the structure of the code and makes code easier to read.

  • Use the pretty listing feature to format code with the the default settings (smart indenting, 4 character indents, save tabs as spaces). For more information, see VB Specific, Basic, Text Editor, Options Dialog Box.

  • Use only one statement per line. Do not use ":".

  • Use only one declaration per line.

  • Indent continuation lines one tab stop.

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

Commenting Conventions

  • Do not use comments at the end of a line of code. Put comments on a separate line.

  • Begin the comment text with an uppercase letter.

  • End the comment with a period.

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

    ' Here is a comment.
    
  • Do not create formatted blocks of asterisks that surround comments.

Program Structure

  • When using 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
    

Language Guidelines

String Data Type

  • Use & to concatenate strings:

    MsgBox("hello" & vbCrLf & "goodbye")
    
  • For appending 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
    

Unsigned Data Type

  • Use Integer rather than unsigned types unless memory is at a premium.

Arrays

  • Use the short syntax when initializing arrays on the declaration line:

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

    Rather than this:

    Dim letters() As String = New String() {"a", "b", "c"}
    
  • Put the array designator on the variable, not on the type:

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

    Rather than this:

    Dim letters As String() = {"a", "b", "c"}
    
  • Use the { } syntax when declaring and initializing arrays of basic data types:

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

    Rather than this:

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

Use the With Keyword

When faced with a series of calls to one object, consider using the With keyword.

Declare Looping Variables in the For or For Each Statement

  • Example:

    For count As Integer = 0 To 2
        MsgBox(names(count))
    Next
    
  • Example:

    For Each name As String In names
        MsgBox(name)
    Next
    

Use Try...Catch

  • Always use a Try...Catch with object that implements a Dispose method.

  • Don’t use On Error Goto.

Use the Using Statement

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

IsNot Keyword

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

Default Instances of Forms

Use Form1.ShowDialog rather than My.Forms.Form1.ShowDialog.

New Keyword

  • Use short instantiation:

    Dim employees As New Collection() 
    

    Rather than this:

    Dim employees As Collection = New Collection()
    
  • Use the parameterless constructor and then set the properties using With:

    Dim orderLog As New EventLog()
    With orderLog
        .Log = "Application"
        .Source = "Application Name"
        .MachineName = "Machine Name"
    End With
    

Event Handling

  • Use Handles rather than AddHandler:

    Private Sub MenuItem1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MenuItem1.Click
    
  • Use AddressOf, and do not instantiate the delegate explicitly:

    Dim closeItem As New MenuItem("Close", AddressOf MenuItem1_Click)
    Me.MainMenu1.MenuItems.Add(closeItem)
    
  • When you define an event, use the short syntax and let the compiler define the delegate:

    Public Event WhatHappened(ByVal source As Object, _
        ByVal e As WhatHappenedEventArgs)
    

Using Shared Members

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

MsgBox Function

Use MsgBox instead of MessageBox.Show or Console.WriteLine.

Use the My Namespace

Use My features in preference to the .NET Framework class library or the Visual Basic run-time library.

Use the Visual Basic Run-Time Library Members

Use the Visual Basic run-time library in preference to the .NET Framework class library.

Guidelines for Samples

General

Localization

  • Use the AutoSize property where possible.

  • Do not hide or overlap controls.

  • Do not line up controls to create a sentence.

  • Do not build strings by stripping out characters from another string.

  • Use culture-neutral graphics.

  • Use only Tahoma or MS Sans Serif fonts.

Accessibility

  • Use colors from the System tab of the color picker dialog box.

  • Use accelerators for all menus, labels, buttons, and so on.

  • Set control properties as described in the following table.

Property Setting

AccessibleDescription

A description of the control.

AccessibleName

A name for the control.

AccessibleRole

Default, or reset this property if a control has another role.

TabIndex

Set in a logical order.

Text

All clickable controls should have a keyboard access key (shortcut).

Font size

Default or set to 10 points or larger

Forecolor

Default

Backcolor

Default

BackgroundImage

Default

Security

Follow the guidelines in Secure Coding Guidelines.

See Also

Other Resources

Design Guidelines for Developing Class Libraries
Secure Coding Guidelines