Saturday, May 18, 2013

Compare Between VB.NET and Visual Basic

Comparative examples

The following simple examples compare VB and VB.NET syntax. Each example creates a "Hello, World" message box with an OK button.
VB6:
Private Sub Command1_Click()
    MsgBox "Hello, World"
End Sub
VB.NET (MsgBox or MessageBox class can be used):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
    MessageBox.Show("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 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 VB6 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 VB6 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 VB6, 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 MsgBox in the Microsoft.VisualBasic namespace which can be used similarly to the corresponding function in VB6. There is a controversy 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 VB 2008, the inclusion of ByVal sender as Object, ByVal e as EventArgs has become optional.
The following example demonstrates a difference between VB6 and VB.NET. Both examples close the active window.
VB6:
Sub cmdClose_Click()
    Unload Me
End Sub
VB.NET:
Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
    Me.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:
VB6:
Sub Timer1_Timer()
    Me.Height = Me.Height - 1
End Sub
VB.NET:
Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
    Me.Height -= 1
End Sub

No comments:

Post a Comment