Visual Basic (.NET)
Visual Basic, originally called Visual Basic.NET, is a multi-paradigm, object-oriented programming language developed by Microsoft and implemented on.NET, Mono, and the.NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visual Basic language, the last version of which was Visual Basic 6.0. Although the ".NET" portion of the name was dropped in 2005, this article uses "Visual Basic " to refer to all Visual Basic languages released since 2002, in order to distinguish between them and the classic Visual Basic. Along with C# and F#, it is one of the three main languages targeting the.NET ecosystem. Microsoft updated its VB language strategy on 6 February 2023, stating that VB is a stable language now and Microsoft will keep maintaining it.
Microsoft's integrated development environment for developing in Visual Basic is Visual Studio. Most Visual Studio editions are commercial; the only exceptions are Visual Studio Express and Visual Studio Community, which are freeware. In addition, the.NET Framework SDK includes a freeware command-line compiler called vbc.exe. Mono also includes a command-line VB.NET compiler.
Visual Basic is often used in conjunction with the Windows Forms GUI library to make desktop apps for Windows. Programming for Windows Forms with Visual Basic involves dragging and dropping controls on a form using a GUI designer and writing corresponding code for each control.
Use in making GUI programs
The Windows Forms library is most commonly used to create GUI interfaces in Visual Basic. All visual elements in the Windows Forms class library derive from the Control class. This provides the minimal functionality of a user interface element such as location, size, color, font, text, as well as common events like click and drag/drop. The Control class also has docking support to let a control rearrange its position under its parent.Forms are typically designed in the Visual Studio IDE. In Visual Studio, forms are created using drag-and-drop techniques. A tool is used to place controls on the form. Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed in the Visual Studio IDE GUI or in code. Many attribute values can be modified during run time by code such as based on user actions, or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.
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 and four iterative execution constructs . TheFor... To statement has separate initialisation and testing sections, both of which must be present. 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.
- The equals sign is used in both assigning values to variables and in comparison.
- Round brackets 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 line is a comment.Simple example
Module Module1
Sub Main
' The classic "Hello, World!" demonstration program
Console.WriteLine
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.
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.
Console.WriteLine
This line performs the actual task of writing the output. Console is a system object, representing a command-line interface 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.
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 AndAlso rows >= 1
WriteLine
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
current += 1
Next
WriteLine
Next
End Sub
'''
Function ReadLine As String
If prompt IsNot Nothing Then
Write
End If
Return Console.ReadLine
End Function
End Module
Comparison with the classic Visual Basic
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, theInteger 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 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. 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 :
Private Sub Button1_Click Handles Button1.Click
MsgBox
End Sub
- Both Visual Basic 6 and Visual Basic.NET automatically generate the
SubandEnd Substatements when the corresponding button is double-clicked in design view. Visual Basic.NET will also generate the necessaryClassandEnd Classstatements. 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 and subs.
- The names
Command1andButton1are not obligatory. However, these are default names for a command button in Visual Basic 6 and VB.NET respectively. - In VB.NET, the
Handleskeyword is used to make the subButton1_Clicka handler for theClickevent of the objectButton1. In Visual Basic 6, event handler subs must have a specific name consisting of the object's name, an underscore, and the event's name. - There is a function called
MessageBox.Showin theMicrosoft.VisualBasicnamespace which can be used similarly to the corresponding function in Visual Basic 6. There is a controversy about which function to use as a best practice. 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 orInteger. - In Visual Basic 2008, the inclusion of, has become optional.
Visual Basic 6:
Sub cmdClose_Click
Unload Me
End Sub
VB.NET:
Sub btnClose_Click 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 Handles Timer1.Tick
Me.Height -= 1
End Sub