Syntax
Visual Basic uses statements to specify actions. The most common statement is an expression statement, consisting of an expression to be evaluated, on a single line. As part of that evaluation, functions or subroutines may be called and variables may be assigned new values. To modify the normal sequential execution of statements, Visual Basic provides several control-flow statements identified by reserved keywords. Structured programming is supported by several constructs including two conditional execution constructs (If ... Then ... Else ... End If and Select Case ... Case ... End Select ) and four iterative execution (loop) constructs (Do ... Loop, For ... To, For Each, and While ... End While) . The For ... To statement has separate initialisation and testing sections, both of which must be present. (See examples below.) The For Each statement steps through each value in a list.
In addition, in Visual Basic:
- There is no unified way of defining blocks of statements. Instead, certain keywords, such as "If ... Then" or "Sub" are interpreted as starters of sub-blocks of code and have matching termination keywords such as "End If" or "End Sub".
- Statements are terminated either with a colon (":") or with the end of line. Multiple-line statements in Visual Basic are enabled with " _" at the end of each such line. The need for the underscore continuation character was largely removed in version 10 and later versions.7
- The equals sign ("=") is used in both assigning values to variables and in comparison.
- Round brackets (parentheses) are used with arrays, both to declare them and to get a value at a given index in one of them. Visual Basic uses round brackets to define the parameters of subroutines or functions.
- A single quotation mark (') or the keyword
REM, placed at the beginning of a line or after any number of space or tab characters at the beginning of a line, or after other code on a line, indicates that the (remainder of the) line is a comment.
Simple example
The following is a very simple Visual Basic program, a version of the classic "Hello, World!" example created as a console application:
Module Module1
Sub Main()
' The classic "Hello, World!" demonstration program
Console.WriteLine("Hello, World!")
End Sub
End Module
It prints "Hello, World!" on a command-line window. Each line serves a specific purpose, as follows:
Module Module1
This is a module definition. Modules are a division of code, which can contain any kind of object, like constants or variables, functions or methods, or classes, but can not be instantiated as objects like classes and cannot inherit from other modules. Modules serve as containers of code that can be referenced from other parts of a program.8
It is common practice for a module and the code file which contains it to have the same name. However, this is not required, as a single code file may contain more than one module or class.
Sub Main()
This line defines a subroutine called "Main". "Main" is the entry point, where the program begins execution.9
Console.WriteLine("Hello, world!")
This line performs the actual task of writing the output. Console is a system object, representing a command-line interface (also known as a "console") and granting programmatic access to the operating system's standard streams. The program calls the Console method WriteLine, which causes the string passed to it to be displayed on the console.
Instead of Console.WriteLine, an alternative is MsgBox, which prints the message in a dialog box instead of a command-line window.10
Complex example
This piece of code outputs Floyd's Triangle to the console:
Imports System.Console
Module Program
Sub Main()
Dim rows As Integer
' Input validation.
Do Until Integer.TryParse(ReadLine("Enter a value for how many rows to be displayed: " & vbcrlf), rows) AndAlso rows >= 1
WriteLine("Allowed range is 1 and {0}", Integer.MaxValue)
Loop
' Output of Floyd's Triangle
Dim current As Integer = 1
Dim row As Integer
Dim column As Integer
For row = 1 To rows
For column = 1 To row
Write("{0,-2} ", current)
current += 1
Next
WriteLine()
Next
End Sub
''' <summary>
''' Like Console.ReadLine but takes a prompt string.
''' </summary>
Function ReadLine(Optional prompt As String = Nothing) As String
If prompt IsNot Nothing Then
Write(prompt)
End If
Return Console.ReadLine()
End Function
End Module
Comparison with the classic Visual Basic
Main article: Comparison of Visual Basic and Visual Basic .NET
Whether Visual Basic .NET should be considered as just another version of Visual Basic or a completely different language is a topic of debate. There are new additions to support new features, such as structured exception handling and short-circuited expressions. Also, two important data-type changes occurred with the move to VB.NET: compared to Visual Basic 6, the Integer data type has been doubled in length from 16 bits to 32 bits, and the Long data type has been doubled in length from 32 bits to 64 bits. This is true for all versions of VB.NET. A 16-bit integer in all versions of VB.NET is now known as a Short. Similarly, the Windows Forms editor is very similar in style and function to the Visual Basic form editor.
The things that have changed significantly are the semantics—from those of an object-based programming language running on a deterministic, reference-counted engine based on COM to a fully object-oriented language backed by the .NET Framework, which consists of a combination of the Common Language Runtime (a virtual machine using generational garbage collection and a just-in-time compilation engine) and a far larger class library. The increased breadth of the latter was also a problem that VB developers had to deal with when coming to the language, although this was somewhat addressed by the My feature in Visual Studio 2005.
The changes altered many underlying assumptions about the "right" thing to do with respect to the performance and maintainability of applications. Some functions and libraries no longer exist; others are available, but not as efficient as the "native" .NET alternatives. Even if they compiled, most converted Visual Basic 6 applications required some level of refactoring to take full advantage of the .NET language. Microsoft provided documentation to cover changes in language syntax, debugging applications, deployment, and terminology.11 A popular trade book designed to ease the transition was Michael Halvorson's Microsoft Visual Basic .NET Professional Step by Step, published in 2002 by Microsoft Press.
Comparative examples
The following simple examples compare VB and VB.NET syntax. They assume that the developer has created a form, placed a button on it and has associated the subroutines demonstrated in each example with the click event handler of the mentioned button. Each example creates a "Hello, World" message box after the button on the form is clicked.
Visual Basic 6:
Private Sub Command1_Click()
MsgBox "Hello, World"
End Sub
VB.NET (MsgBox or MessageBox class can be used):
Private Sub Button1_Click(sender As object, e As EventArgs) Handles Button1.Click
MsgBox("Hello, World")
End Sub
- Both Visual Basic 6 and Visual Basic .NET automatically generate the
Sub and End Sub statements when the corresponding button is double-clicked in design view. Visual Basic .NET will also generate the necessary Class and End Class statements. The developer need only add the statement to display the "Hello, World" message box. - All procedure calls must be made with parentheses in VB.NET, whereas in Visual Basic 6 there were different conventions for functions (parentheses required) and subs (no parentheses allowed, unless called using the keyword
Call). - The names
Command1 and Button1 are not obligatory. However, these are default names for a command button in Visual Basic 6 and VB.NET respectively. - In VB.NET, the
Handles keyword is used to make the sub Button1_Click a handler for the Click event of the object Button1. In Visual Basic 6, event handler subs must have a specific name consisting of the object's name (Command1), an underscore (_), and the event's name (Click, hence Command1_Click). - There is a function called
MessageBox.Show in the Microsoft.VisualBasic namespace which can be used (instead of MsgBox) similarly to the corresponding function in Visual Basic 6. There is a controversy12 about which function to use as a best practice (not only restricted to showing message boxes but also regarding other features of the Microsoft.VisualBasic namespace). Some programmers prefer to do things "the .NET way", since the Framework classes have more features and are less language-specific. Others argue that using language-specific features makes code more readable (for example, using int (C#) or Integer (VB.NET) instead of System.Int32). - In Visual Basic 2008, the inclusion of
ByVal sender as Object, ByVal e as EventArgs has become optional.
The following example demonstrates a difference between Visual Basic 6 and VB.NET. Both examples close the active window.
Visual Basic 6:
Sub cmdClose_Click()
Unload Me
End Sub
VB.NET:
Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Close()
End Sub
The 'cmd' prefix is replaced by the 'btn' prefix, conforming to the new convention previously mentioned.
Visual Basic 6 did not provide common operator shortcuts. The following are equivalent:
Visual Basic 6:
Sub Timer1_Timer()
'Reduces Form Height by one pixel per tick
Me.Height = Me.Height - 1
End Sub
VB.NET:
Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Me.Height -= 1
End Sub
Comparison with C#
Main article: Comparison of C Sharp and Visual Basic .NET
C# and Visual Basic are Microsoft's first languages made to program on the .NET Framework (later adding F# and more; others have also added languages). Though C# and Visual Basic are syntactically different, that is where the differences mostly end. Microsoft developed both of these languages to be part of the same .NET Framework development platform. They are both developed, managed, and supported by the same language development team at Microsoft.13 They compile to the same intermediate language (IL) known as CIL, which runs against the same .NET Framework runtime libraries.14 Although there are some differences in the programming constructs, their differences are primarily syntactic and, assuming one avoids the Visual Basic "Compatibility" libraries provided by Microsoft to aid conversion from Visual Basic 6, almost every feature in VB has an equivalent feature in C# and vice versa. Both languages reference the same Base Classes of the .NET Framework to extend their functionality, and both languages can reference compiled code written in the other language. As a result, with few exceptions, a program written in either language can be run through a simple syntax converter to translate to the other. There are many open source and commercially available products for this task.
Version history
Succeeding the classic Visual Basic version 6.0, the first version of Visual Basic .NET debuted in 2002. As of 2020, ten versions of Visual Basic .NET are released.
2002 (VB 7.0)
The first version, Visual Basic .NET, relies on .NET Framework 1.0. The most important feature is managed code, which contrasts with the classic Visual Basic.
2003 (VB 7.1)
Visual Basic .NET 2003 was released with .NET Framework 1.1. New features included support for the .NET Compact Framework and a better VB upgrade wizard. Improvements were also made to the performance and reliability of .NET IDE (particularly the background compiler) and runtime. In addition, Visual Basic .NET 2003 was available in the Visual Studio.NET Academic Edition, distributed to a certain number of scholars from each country without cost.
2005 (VB 8.0)
After Visual Basic .NET 2003, Microsoft dropped ".NET" from the name of the product, calling the next version Visual Basic 2005.
For this release, Microsoft added many features intended to reinforce Visual Basic .NET's focus as a rapid application development platform and further differentiate it from C#., including:
- Edit and Continue feature
- Design-time expression evaluation
- A pseudo-namespace called "My", which provides:1516
- Easy access to certain areas of the .NET Framework that otherwise require significant code to access like using
rather than