Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Visual Basic (.NET)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Syntax == {{Expand section|date=April 2014}} Visual Basic uses [[Statement (computer science)|statements]] to specify actions. The most common statement is an expression statement, consisting of an [[Expression (computer science)|expression]] to be evaluated, on a single line. As part of that evaluation, [[subroutine|functions or subroutines]] may be [[System call|called]] and [[Variable (programming)|variables]] may be [[assignment (computer science)|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 (<code>If</code> ... <code>Then</code> ... <code>Else</code> ... <code>End If</code> and <code>Select Case</code> ... <code>Case</code> ... <code>End Select</code> ) and four iterative execution (loop) constructs (<code>Do</code> ... <code>Loop</code>, <code>For</code> ... <code>To</code>, <code>For Each</code>, and <code>While</code> ... <code>End While</code>) . The <code>For</code> ... <code>To</code> statement has separate initialisation and testing sections, both of which must be present. (See examples below.) The <code>For Each</code> 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 (punctuation)|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.<ref>{{cite web |url=https://msdn.microsoft.com/en-us/library/ff637436.aspx |title=New Features in Visual Basic 10 |date=June 3, 2010 |access-date=September 5, 2015 |archive-date=March 4, 2016 |archive-url=https://web.archive.org/web/20160304231731/https://msdn.microsoft.com/en-us/library/ff637436.aspx |url-status=live }}</ref> * The [[equals sign]] ("=") is used in both assigning values to variables and in comparison. * [[Parentheses|Round brackets]] (parentheses) are used with [[Array data structure|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 <code>REM</code>, placed at the beginning of a line or after any number of [[Space character|space]] or [[Tab character|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 (computer programming)|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: <syntaxhighlight lang="vbnet"> Module Module1 Sub Main() ' The classic "Hello, World!" demonstration program Console.WriteLine("Hello, World!") End Sub End Module </syntaxhighlight> It prints "''Hello, World!''" on a [[command-line interface|command-line window]]. Each line serves a specific purpose, as follows: <syntaxhighlight lang="vbnet"> Module Module1 </syntaxhighlight> 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.<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/aaxss7da(VS.80).aspx |title=Module Statement |publisher=MSDN – Developer Center |access-date=January 20, 2010 |archive-date=January 9, 2010 |archive-url=https://web.archive.org/web/20100109092122/http://msdn.microsoft.com/en-us/library/aaxss7da(VS.80).aspx |url-status=live }}</ref><br />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. <syntaxhighlight lang="vbnet"> Sub Main() </syntaxhighlight> This line defines a subroutine called "Main". "Main" is the entry point, where the program begins execution.<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/ms235406(VS.80).aspx |title=Main Procedure in Visual Basic |publisher=MSDN – Developer Center |access-date=January 20, 2010 |archive-date=January 28, 2010 |archive-url=https://web.archive.org/web/20100128090733/http://msdn.microsoft.com/en-us/library/ms235406(VS.80).aspx |url-status=live }}</ref> <syntaxhighlight lang="vbnet"> Console.WriteLine("Hello, world!") </syntaxhighlight> 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, one could use MsgBox, which prints the message in a dialog box instead of a command-line window.<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/3cf7t4xt(VS.80).aspx |title=Visual Basic Version of Hello, World |publisher=MSDN – Developer Center |access-date=January 20, 2010 |archive-date=January 11, 2010 |archive-url=https://web.archive.org/web/20100111152427/http://msdn.microsoft.com/en-us/library/3cf7t4xt(VS.80).aspx |url-status=live }}</ref> === Complex example === This piece of code outputs [[Floyd's Triangle]] to the console: <syntaxhighlight lang="vbnet"> 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 </syntaxhighlight> === Comparison with the classic Visual Basic === {{Main|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 [[exception handling|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 <code>Integer</code> [[data type]] has been doubled in length from 16 bits to 32 bits, and the <code>Long</code> [[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 <code>Short</code>. 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 counting|reference-counted]] engine based on [[Component Object Model|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 [[Garbage collection (computer science)#Generational GC (aka Ephemeral GC)|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.<ref>{{cite web|url = http://msdn.microsoft.com/en-us/vstudio/ms788233|title = Microsoft Visual Basic 6.0 Migration Resource Center|access-date = November 9, 2014|website = [[MSDN]]|publisher = [[Microsoft]]|archive-date = November 9, 2014|archive-url = https://web.archive.org/web/20141109140433/http://msdn.microsoft.com/en-us/vstudio/ms788233|url-status = live}}</ref> A popular trade book designed to ease the transition was [[Michael Halvorson|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: <syntaxhighlight lang="vbscript"> Private Sub Command1_Click() MsgBox "Hello, World" End Sub </syntaxhighlight> VB.NET (MsgBox or MessageBox class can be used): <syntaxhighlight lang="vbnet"> Private Sub Button1_Click(sender As object, e As EventArgs) Handles Button1.Click MsgBox("Hello, World") End Sub </syntaxhighlight> * Both Visual Basic 6 and Visual Basic .NET automatically generate the <code>Sub</code> and <code>End Sub</code> statements when the corresponding button is double-clicked in design view. Visual Basic .NET will also generate the necessary <code>Class</code> and <code>End Class</code> 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 <code>Call</code>). * The names <code>Command1</code> and <code>Button1</code> are not obligatory. However, these are default names for a command button in Visual Basic 6 and VB.NET respectively. * In VB.NET, the <code>Handles</code> keyword is used to make the sub <code>Button1_Click</code> a handler for the <code>Click</code> event of the object <code>Button1</code>. In Visual Basic 6, event handler subs must have a specific name consisting of the object's name ({{code|Command1}}), an underscore ({{code|_}}), and the event's name ({{code|Click}}, hence {{code|Command1_Click}}). * There is a function called <code>MessageBox.Show</code> in the <code>Microsoft.VisualBasic</code> namespace which can be used (instead of <code>MsgBox</code>) similarly to the corresponding function in Visual Basic 6. There is a controversy<ref>{{cite web|url=https://www.microsoft.com/en-us/download/details.aspx?id=55979|title=Visual Studio 2003 Retired Technical documentation|website=Microsoft Download Center|access-date=July 24, 2018|archive-date=December 30, 2014|archive-url=https://web.archive.org/web/20141230014657/http://msdn.microsoft.com/en-us/library/aa291820(VS.71).aspx|url-status=live}}</ref> about which function to use as a best practice (not only restricted to showing message boxes but also regarding other features of the <code>Microsoft.VisualBasic</code> 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 <code>int</code> (C#) or <code>Integer</code> (VB.NET) instead of <code>System.Int32</code>). * In Visual Basic 2008, the inclusion of {{code|2=vbnet|ByVal sender as Object}}, {{code|2=vbnet|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: <syntaxhighlight lang="vbscript"> Sub cmdClose_Click() Unload Me End Sub </syntaxhighlight> VB.NET: <syntaxhighlight lang="vbnet"> Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click Close() End Sub </syntaxhighlight> The 'cmd' prefix is replaced by the 'btn' prefix, conforming to the new convention previously mentioned.{{Which|date=November 2014}} Visual Basic 6 did not provide common operator shortcuts. The following are equivalent: <!-- Visual Basic 6 did NOT have an opacity setting for forms or any other standard control --> Visual Basic 6: <syntaxhighlight lang="vbscript"> Sub Timer1_Timer() 'Reduces Form Height by one pixel per tick Me.Height = Me.Height - 1 End Sub </syntaxhighlight> VB.NET: <syntaxhighlight lang="vbnet"> Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Me.Height -= 1 End Sub </syntaxhighlight> === Comparison with C# === {{Main|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 Sharp (programming language)|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.<ref>{{cite web |last=Krill |first=Paul |url=http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |archive-url=https://archive.today/20130126074556/http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |url-status=dead |archive-date=January 26, 2013 |title=Microsoft converging programming languages | Developer World |publisher=InfoWorld |date=February 27, 2009 |access-date=August 18, 2013 }}</ref> They compile to the same intermediate language (IL), which runs against the same .NET Framework runtime libraries.<ref>{{cite web |url=http://www.dotnet-guide.com/msintermediate.html |title=Microsoft Intermediate Language |publisher=Dotnet-guide.com |access-date=August 18, 2013 |archive-date=June 2, 2013 |archive-url=https://web.archive.org/web/20130602151947/http://www.dotnet-guide.com/msintermediate.html |url-status=live }}</ref> 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. Lastly, both languages reference the same Base Classes of the .NET Framework to extend their functionality. 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.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)