Visual Basic .NET


Visual Basic .NET is a programming language with syntax similar to that of Visual Basic 6 .

VB.NET allows to develop in .NET via Visual Studio , on Windows operating systems (98, 2000, XP, Vista, 7, 8, 8.1 and 10). Like any other language on the .NET platform, VB.NET is compiled to the CIL intermediate language .

IDEs (development environments)

Screenshot of MonoDevelop

The common and unavoidable IDE of all .NET languages ​​is Visual Studio . This one is paid for but has a free version for developers and small companies (turnover less than one million dollars) named Visual Studio Community.

Another free version exists, limited to a single language: Visual Studio Express .

Other free IDEs exist, such as SharpDevelop or MonoDevelop , but these are less advanced than Visual Studio.

Versions

Evolutions: from VB6 to VB7 (non-exhaustive)

What differentiates VB6 ( Visual Basic 6) from VB7 ( Visual Studio 2003)? :

  • Object orientation emerged including the integration of the technology of the legacy , which to date limited industrialization Visual Basic code (VB6 is not an object oriented language proper).
  • Integration of the development environment (IDE) into the Visual Studio suite to use other languages ​​such as Visual C ++ or Visual C # . A function library made in C # will be fully compatible and usable in a VB.NET application.
  • The code produced by VB.NET is compiled in the same intermediate language called the Common Intermediate Language ( CIL ) or Microsoft Intermediate Language (MSIL). This language is the same as the result of a C # compilation.
  • The connection to the database is facilitated by improved tools dragging and using the latest technology ADO , ADO.NET.
  • The XML technology is natively integrated in .NET, allowing easier creation of online application or data backup.
  • The SQL code generator is much more powerful.
  • Writing error handlers allows Multithreading via TRY / CATCH blocks.
  • The scope of the GOTO instructions is limited (jumps can only be done within the same function). This behavior is due to the operation of the .NET platform itself and is common to all .NET languages: C #, J #, and so on.
  • Declaring variables is made mandatory by default (unlike Visual Basic 6 where this feature was disabled by default).
  • The integration of new .NET object classes has been done while allowing for intermediate versions to reuse .COM objects making migration easier from Visual Basic 6 to VB Net. VB.NET is the only language of .NET to have an “in-depth” integration of COM objects.
  • Pointers to functions can and must (in 99% of cases) now be typed (notion of delegates).

Evolutions: VB7 to VB8 (non-exhaustive)

Some innovations have made their appearances between VB7 and VB8, but it is especially the passage of the framework .NET 1.1 to 2.0 that marks this evolution.

Here is a summary:

  • The partial classes, allowing to distribute the implementation of a class on several files.
  • Generic types, typical evolution of C ++ templates.
  • The “nullable” types, ie the ability to specify that a value type can be null. These are declared with the question mark character “?” ” Dim X as Integer? = NothingFollowing the type name, like this: (VB9) or with a particular class (VB8 +). This value “Nothing” would be, if the “? “Was not specified, converted to 0 in this case. In the new system, (X + 10) would be worth “Nothing” (Nothing is absorbing in all operators), and not as it would have been otherwise. Any member with an “empty” value is “empty”.
  • The documentation is automatically generated from special comments in the code.

Evolutions: VB8 to VB9 (non-exhaustive)

VB9 has obviously implemented all the new features of C #, as well as some others:

  • LINQ, XLINQ, DLINQ …
  • Expression Trees (anonymous functions)
  • Relaxed conversions between delegates
  • XML Literal  [ archive ]
  • Introduction of the ternary IF (equivalent of bool? TruePart: falsePart), optimized with respect to IIF ()
  • The migration of the VB6 to .NET code and the backward compatibility with this language (Class VB6) have been removed.

Evolutions: VB9 to VB10

VB10 (also called VBx) marks a major turning point in the evolution of VB. In addition to the fact that it will be integrated in Framework 4, it should above all completely fill its “delay” with respect to C # on certain points (just as C # will fill its delay towards VB), since the “coevolution” of the C # languages ​​and VB.NET has been officially announced. This not only ensures a stable future for VB.NET, which can not be forsaken by Microsoft but also a guarantee that everything that is feasible in C # will always be synonymous with VB.NET (even if it is another way).

The features provided for VBx:

  • Dynamic objects (notably allows for prototype- oriented programming and communication between dynamic languages ​​( JScript …) and the languages ​​of the .NET platform)
  • Implicit interfaces management (like C #)
  • Managing anonymous methods
  • Simplification of the writing of tables, collections, lists and dictionaries.

Some differences between C # and VB.NET (non-exhaustive)

Here are the most obvious differences between VB.NET and C # (VB.NET and C # evolving, the elements of this list may be obsolete):

  • VB supports optional parameters (C # only supports version 4)
  • VB supports “late-binding” (calling a property / function with its name, without knowing the type of the object (for COM objects))
  • The Microsoft.VisualBasic namespace gives compatibility with VB6. It is to be avoided if a more efficient solution exists.
  • The “My” space implements many WMI or IO calls, as well as several “shortcuts” in the management of resources and application settings. (VB8 +)
  • VB supports structure With
  • Simplified event management in windows and controls
  • We can define an interface method with a different name than the one proposed initially (if we want to redefine a function in the class with the same name but a different action)
  • Support keyword When in the Catch block (eg Catch ex as ComException When ex.ErrNumber = 30)
  • XML Literal is not implemented in C #.
  • Custom Events are not implemented in C #.

A list of the differences (in 2005) between C # and VB.NET more complete exists here  [ archive ] .

Some examples of code in VB.NET

Hello World in VB.NET (Mode Console)

Public Module HelloWorld
 'The following lines are all optional, but advised
 ' They are automatically transformed into documentation
 '' <summary> Program entry point </ summary>
 '' '<param name = "Args"> Command passed to program </ param>
 Public Sub Main ( ByVal Args As String ()
 'Write to console
 console . WriteLine ( "Hello World!" )
 'Wait for the user to press a
 Console key . ReadKey ( False )
 End Sub
End Module

Hello World in VB.NET (Windows Forms Mode)

Public Class Form1
 Public Sub DisplayMessage ()
 '1st solution (also works in VBScript)
 MsgBox ( "Hello World!" )
 2nd
 MessageBox solution . Show ( "Hello World!" )
 'Other design
 MsgBox ( "Hello World" , MsgBoxStyle . Critical , "Title, hello world" )
 OU
 MsgBox ( "Hello World" , MsgBoxStyle . Information , "Title, hello world"

Loops and conditions

'
' A simple IF condition
'
If XCondition = 3 Then
 ' XCondition is worth 3
ElseIf YCondition <> 4 Then
 'XCondition is not 3
 ' YCondition is not worth 4
ElseIf ZCondition Is AnotherObject
 'XCondition is not 3
 ' YCondition is 4
 'ZCondition And AnotherObject return to the same
Else
 object 'None of the previous conditions was encountered
End If
'
' A Select Case optimized (Switch C #)
'
Select Case X
 Case 0
 ' = 0 X
 Case 1
 X = 1
 Case 2
 'X 2 =
 Case Else
 ' X <> 1
End select
'
' A SELECT CASE translated to IF / ELSE IF at compilation
'
Select Case Y
 Case Is < 3
 ' Y <3
 Case 3
 'Y = 3
 Case Else
 ' Y> 3 in this case
End Case
'
' WHILE loop
'
While ImTrue
 ' ImTrue is true
 'Here we change the value of ImTrue
 ImTrue = False
End While
' ImTrue is no longer true
'
Loop Do ... Loop
'
ImFalse = False
Do
 'No condition was applied if this is the first time
 ' Otherwise, ImFalse is not false
 'In this example, Is not
restarted a loop Until ImFalse = False
'ImFalse is wrong
'
' Loops For and For Each
'
For X As Integer = 0 to 9
 ' This code will be executed 10 times
Next
For X As Integer = 10 TB 1 Step - 1
 'This code will be executed 10 times in the opposite
direction Next
For Each Element As ElementType In Array
 'This code will be executed as many times as there are ElementType elements in Array
Next

The tables

'Create an array of text, empty and infinite size
Dim Table () As String
' Create a table of natural numbers, empty and infinite size
Dim Table () As Integer
'Create an array of real numbers, empty and infinite size
Sun Table () As Double
'Assign a value to the first box of the array
Table ( 0 ) = "Table box"
Table ( 0 ) = 1
Table ( 0 ) = 1.5
'Create an array of two lines of text and two text columns and empty
Sun Table ( 1 , 1 ) As String
' Create a text table with two columns and one row with "Hello" and "Goodbye"
Sun Table () As String = { "Hello" , "goodbye" }
'Create two columns of text panel and two lines
Sun Table (,) As String = {{ "column 1, line 1" , "Column 2, line 1" }, { "Column 1, Line 2 " , " Column 2, Line 2 " }}
'' Create a table and then resize the safeguarding values
'Create a table of ten lines and ten columns
Dim Table ( 9 , 9 ) As String
' Resize twenty rows and twenty columns preserving the values
Redim Preserve Table ( 19 , 19 )
'Erase all table values ​​by retrieving the space
Erase Table
' Reset Table Array from Element 1 and for 5
Array Elements . Clear ( Table , 1 , 5 )

Exception Management

VB.NET has the try and catch statements to handle exceptions (unexpected behavior of program instructions).

Examples:

Try
 My . Computer . FileSystem . FileReadBytes ( "C: \ Path \ File.ext" )
Catch Ex as FileNotFoundException For Error File not found
 MessageBox . Show ( "Can not find file" , "Error" )
Catch Ex as Exception 'For other errors.
 Messagebox . Show ( "An unknown error has occurred, Error returned:" & ex . Message , "Error" )
End Try
'Note that ex retrieves data
from the error, allowing it to be processed.
'There are other options than Message. See the Visual Basic .NET documentation for more information.
Try
 SomeUnknownCOMObject . DoSomething ()
Catch Ex as COMExcpetion When Ex . ErrorCode = 4
 '
 HRESULT 4, which is possible with the
 documentation of the object says (it's an example).
 MessageBox . Show ( "Object was not ready" )
 'Throw some new Application-Specific error.
 Throw new Exception ( "The object was not ready." )
Catch Ex as Exception
 '
 Display some MessageBox message . Show ( "An unknown error occurred" , "Error" )
 'But throw the (same) except
 Throw
Finally
 ' Whatever happens, we do that
 'Even if an error occurred, this code will be launched
 Try : SomeUnkwnowCOMOBject . DoSomethingAnyWay () : Catch ex as Exception : End Try
End Try

Example of using LINQ

'Returns an enumerator that returns all names of child windows that are text editors
' Visual Studio 2008 finds the type of the variable automatically, similar to the "var" of the C #
Dim AllText = From CW in MyFormInstance . ChildWindows
 Where CW . GetType () is GetType ( MyTextEditorWindow )
 Select CW . Text
'Creates an XML object (an XML document, not a string)
' Visual Studio 2008 finds the type of the variable automatically, similar to the C #
Dim var ' XMLDoc = _
 <root> < % For Each Item in Items % >
 < item name = "<% = Item.Name%>" />
 < % Next % > </ root >
'Save to file the XML document
XMLDoc . Save ( "FileName.xml" )

Example of a simple event

'Declaring Objects (Functions, Events, ...) for the Form1
Public Class Form1
 'When the user clicks on the Button1
 Private Sub Button1_Click object ( ByVal sender As System . Object , ByVal e As System . EventArgs ) Handles Button1 . Click
 Me . Close () 'Closes the parent window (thanks to Me) so the
 End Sub
End Class

Example of a code calling a function

Public Class Form1
 'Creating the exit function with Private Sub
 Private Sub Quit ()
 Me . Close ()
 End Sub
 'When the user clicks on the Button1
 Private Sub Button1_Click object ( ByVal sender As System . Object , ByVal e As System . EventArgs ) Handles Button1 . Click
 Call Quit () 'Private Sub Quit ()
 End Sub
 'When the user clicks on the Button2
 Private Sub Button2_Click object ( ByVal sender As System . Object , ByVal e As System . EventArgs ) Handles Button2 . Click
 Call Quit () 'The advantage of this code is that you can call Quit () as many times as you want
 End Sub
End Class