ARTICLE

Visual Basic .NET for VB 6.0 Developers

Posted by Mahesh Chand Articles | VB.NET Articles April 04, 2003
Visual Basic .NET is a major component of Microsoft Visual Studio .NET suite. The .NET version of Visual Basic is a new improved version with more features and additions. After these new additions, VB qualify to become a full object-oriented language such as C++. In this article, I will try to introduce you to VB.NET and will cover new additions to the language. I will also compare VB 6.0 and VB.NET and how to develop simple applications in VB.NET.
 
Reader Level:

Visual Basic .NET is a major component of Microsoft Visual Studio .NET suite. The .NET version of Visual Basic is a new improved version with more features and additions. After these new additions, VB qualify to become a full object-oriented language such as C++. In this article, I will try to introduce you to VB.NET and will cover new additions to the language. I will also compare VB 6.0 and VB.NET and how to develop simple applications in VB.NET. 

1.1 What's VB.NET?

VB.NET is the following version of VB 6.0. Microsoft .NET is a new programming and operating framework introduced by Microsoft. All .NET supported languages access a common .NET library to develop applications and share common tools to execute applications. Programming with Visual Basic using .NET is called VB.NET.

First, I'll show you how to write simplest console based "Hello World" application in VB.NET.

1.2 Hello, World!

"Hello World!" has been a symbol of writing your first Windows applications. Our first program is "Hello VB.NET World!". This program writes an output on the console saying "Hello VB.NET World!". The program looks like Listing 1.1.

Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello VB.NET World!")
End Sub
End
Module

Listing 1.1: Hello VB.NET World Sample

1.3 VB.NET Editors and Compilers

You can type the above code in any text editor such as NotePad or VS.NET IDE and save the file as HelloWorld.vb.

Once the file is saved, you can compile this from command line or using any IDE including VS.NET IDE. VB.NET compiler, vbc.exe ships with Microsoft .NET Framework SDK. You can access it either through an IDE or from command line. IDE generally provides you an option to compile your program from a menu or toolbar.

To compile "HelloWord.vb" from command line, you need to type following command:

vbc HelloWorld.vb /out:HelloWorld.exe /t:exe

After compiling your code, VB compiler creates an exe HelloWorld.exe under the current directory. Now you execute exe from Windows explorer or command line. Did you see "Hello VB.NET World!" on your console? Yes?? Congratulations. You are now officially a VB.NET programmer.

The Imports Statement

As you've seen earlier, most of the .Net types are defined in namespaces. A namespace is a scope in which managed types are defined. If you see .NET Framework Class Library, you'll see hundreds of namespace. For example, System namespace contains types such as Console, Object and so on. If you want to access Console class, you need to import System namespace in your application by using Imports directive. For example, if you want to use the Console class, which is defined in the System namespace, you need to add the following line in your application:

Imports System

You can even call a namespace explicitly without using Imports keyword. The below sample example shows you "Hello World!" example without Imports namespace.

Module Module1
Sub Main()
System.Console.WriteLine("Hello VB.NET World!")
End Sub
End
Module

Listing 1.: Hello VB.NET World Sample

1.4 Description - "Hello VB.NET World!"

The first line of your program is "Imports System".

Imports System ;

The .NET framework class library is referenced in namespaces. The System namespace contains the Console class, which is used to read from or write to the console.

Next you define a module:

Module Module1
....
End Module

Every VB application contains a Main() method, which is the entry point of an application. In our sample example, we call Console.WriteLine() to write "Hello VB.NET World!" on the console.

Sub Main()
Console.WriteLine("Hello VB.NET World!")
End Sub

The WriteLine(), a method of the Console class, writes a string followed by a line terminator to the console. The Console class is defined in the System namespace. You can access its class members by referencing them directly.

The Console class is used to read and write to or from the system console. The Read and ReadLine method are used to read data from the console and the Write and WriteLine methods are used to write data on the console.

Method Description Example
Read Reads a single character

int i = Console.Read();

ReadLine Reads a line string str = Console.ReadLine();
Write Writes a line Console.Write("Write: 1");
WriteLine Writes a line followed by a line terminator.. Console.WriteLine("Test Output Data with Line");

Table 1.1

1.5 What's new in VB.NET?

VB.NET, the following version of VB 6.0 is an improved, stable, and full Object Oriented language. If you remember, in VB 6.0 wasn't a true object-oriented language because there was no support for inheritance, overloading, and interfaces. VB.NET supports inheritance, overloading, and interfaces. Multithreading and Exception handling was two major weeks areas of VB 6.0. In VB.NET, you can develop multithreaded applications as you do in C++ and C# and it also supports structured exception handling. We'll see all these topics in more details later in this chapter.

Here is list of VB.NET features -

  • Object Oriented Programming language.
  • Support inheritance, overloading, interfaces, shared members and constructors.
  • Supports all CLS features such as accessing and working with .NET classes, interaction with other .NET languages, meta data support, common data types, and delegates.
  • Multithreading support.
  • Structured exception handling.

1.6 Namespaces and Assemblies

We just discussed our first VB.NET program, "Hello, World!". The first new thing you notice in this program is a namespace. In .NET references documentation, you see each class belongs to a namespace. What actually is a namespace?

A namespace is a logical grouping of classes or components. To define .NET classes in a category, so they would be easy to recognize, Microsoft utilized C++ class packaging concept known as namespaces. A component in .NET framework is called an assembly. All .NET code is defined in hundreds of libraries (dlls). A namespace organizes the classes defines in an assembly. A namespace can have more than one assembly or an assembly can be defined in more than one namespaces.

The root of all namespaces is System namespace. If you see namespaces in .NET library, each class is defined in a group of similar category. For example, System.Data namespace only possesses data related classes. In the same regard, System.Multithreading contains only multithreading classes.

When you create a new application using any .NET supported language (C#, VB.NET, or C++.NET), you'll notice that each application is defined as a namespace and all classes belong to that namespace. You can access these classes from other applications by referencing their namespace.

In .NET, the actual code is compiled in Intermediate Language (IL), and an assembly stores the IL code, metadata, and other resource files. An assembly can be hosted in one or more exes or Dlls. All .NET libraries are stored in assemblies.

Where do the compiled namespaces reside?

In .NET, the actual code is compiled in Intermediate Language (IL), and an assembly stores the IL code, metadata, and other resource files. An assembly can be hosted in one or more exes or Dlls. All .NET libraries are stored in assemblies.

1.7 VB.NET: A Full Object Oriented Language

Abstraction, Encapsulation, Polymorphism, and Inheritance are four basic properties of an object-oriented language. VB 6.0 supports all of these properties but Inheritance. Now VB.NET supports Inheritance. This brings VB.NET in object-oriented languages category such as C++.

Classes and Modules

VB.NET has Class keyword followed by End Class. This Class..End Class pair creates a class. Each VB.NET program has at least one Module. A module is declared with Module, End Module pair. The main module of an application has a Main method, which is the entry point of the application.

Method can be created in Vb.NET using Function or Sub keywords as they used to be in VB 6.0. The following example shows, how to create a class, add a method, and call it from the main program.

Imports System
Module Module1
Sub Main()
Dim cls As TestClass = New TestClass()
Console.WriteLine(cls.MyMethod)
End Sub
End
Module
Class
TestClass
Function MyMethod() As String
Return
"Test Method!"
End Function
End
Class

Properties

Properties are the public representation of the variables of a class. The Property, End Property statement is used to create a property. The Get and Set methods of property are used to get and set the property values. In the below example, Data is a property of TestClass.

Imports System
Imports System.Console
Module Module1
Sub Main()
Dim cls As TestClass = New TestClass()
WriteLine(cls.MyMethod)
WriteLine(cls.Data)
cls.Data = "New Data"
WriteLine(cls.Data)
End Sub
End
Module
Class TestClass
Private strData As String = "Some Data"
Function MyMethod() As String
Return
"Test Method!"
End Function
' Adding Data property to the class
Public Property Data() As String
Get
Return
strData
End Get
Set
(ByVal Value As String)
strData = Value
End Set
End
Property
End
Class

Overloading

VB.NET supports method overloading using the overload keyword. Using this keyword, you can declare same method names with different arguments.

Scope of a Class Member

Besides Private and Public, VB.NET introduces few new keywords. The following keywords are used to define scope of a class member.

Keyword Scope
Private Scope is limited to the defined class only.
Public Object can be called from the outside of the class.
Friend Scope is limited to the application in which class is defined.
Protected Available to the class and it's derived classes.
Protected Friend Available to the class, the application, and the derived classes.

Inheritance

Inheritance is one of the most used techniques in an object-oriented language. Inheritance provides you to reuse your work. Inheritance provides ability to use an existing class's functionality via it's derived (inherited) class.

VB.NET supports inheritance, which wasn't supported in VB 6.0 and its previous versions. The good thing about inheritance is, you can use any classes either developed by you or somebody else, derive your classes from those classes, and use their class's functionality via your classes. In the below example, Class B is derived from Class A. We are calling A's method MethodA via class B.

Imports System
Imports System.Console
Module Module1
Sub Main()
Dim bObj As B = New B()
WriteLine(bObj.MethodA())
End Sub
End
Module
' Class A defned
Public Class A
Function MethodA() As String
Return
"Method A is called."
End Function
End
Class
'Class B, inherited from Class A. All members (Public and Protected)
' can be access via B now.
Public Class B
Inherits A
Function MethodB() As String
Return
"Method B is called."
End Function
End
Class

You can derive multiple classes from a class or a class from multiple classes.

Shared Members

Shared members of a class are shared by all instances of a class. Shared members can be properties, methods, or fields. Shared members are useful when you dont want to give control to the user. For example, say you developed a library and you don't want to give the control to the user but want them to use some of your library functions.

You can reference the member by using class itself, no the instance. For example,

Module Module1
Sub Main()
WriteLine(A.MethodA())
End Sub
End
Module
' Class A defined
Public Class A
Shared Function MethodA() As String
Return
"Method A is called."
End Function
End
Class

Multithreading

Creating free-threaded applications was one of the lacking area of VB language. In .NET framework, all languages share Common Runtime Library. That means you can develop it applications using VB.NET as you can do with C# or other .NET languages.

The System.Threading namespace defines the threading classes. So we need to import System.Threading namespace before using any threading classes.

The System.Threading.Thread class represents a Thread object. You can create or kill threads using the Thread class.

Creating Threads

Creating an instance of the Thread class creates a new thread and Thread.Start method starts the thread. A thread constructor take an argument of the procedure you want to execute in the thread. For example, in the following example, I want to execute procedure SecondThread in the secondary thread oThread1. oThread1 is an instance of Thread class.

oThread1 = New Thread(AddressOf SecondThread)
SecondThread procedure looks like below:
Public Sub SecondThread()
Dim i As Integer
For
i = 1 To 10
Console.WriteLine(i.ToString())
Next
End
Sub

Now call of Thread.Start() will start the thread.

oThread1.Start()

The below sample example starts two secondary threads.

Imports System
Imports System.Threading
Module Module1
Public oThread1 As Thread
Public oThread2 As Thread
Sub Main()
oThread1 = New Thread(AddressOf SecondThread)
oThread2 = New Thread(AddressOf ThirdThread)
oThread1.Start()
oThread2.Start()
End Sub
Public Sub SecondThread()
Dim i As Integer
For
i = 1 To 10
Console.WriteLine(i.ToString())
Next
End
Sub
Public Sub ThirdThread()
Dim i As Integer
For
i = 1 To 10
Console.WriteLine("A" + i.ToString())
Next
End
Sub
End
Module

Killing a Thread

Abort method is called to kill a thread permanently. Make sure you call IsAlive before Abort.

If Thread1.IsAlive Then
Thread1.Abort()
End If

Pausing a thread

You can use Sleep method to pause a thread. Sleep method takes an argument of milliseconds. The following example will make thread sleep for one second.

Thread2.Sleep(1000)

You can even use Suspend and Resume methods to suspend and resume a thread.

Setting priority of Threads

Thread class's Priority property is used to sets thread's priority. The thread priority can have Normal, AboveNormal, BelowNormal, Highest, and Lowest values.

Thread2.Priority = ThreadPriority.Highest

Threads and Apartments

ApartmetnState property let you set the apartment type of the thread. It can be STA, MTA, or Unknown.

Thread.ApartmentState = ApartmentState.MTA

MTA means the thread will be hosted in a is multi-threaded apartment and STA means single threaded.

public enum ApartmentState
{
STA = 0,
MTA = 1,
Unknown = 2,
};

1.8 Structured Exception Handling

Exception handling is also called error handling. As a VB programmer, you must be familiar with On Error Goto and On Error Resume Next statements we used to handler errors in VB 6.0. This exception handling in VB is called Unstructured Exception Handling. In VB.NET, Microsoft introduces Structured Error Handling controls. Vb.NET supports C++ like Try..Catch..Finally control. The structure of try..catch..finally looks like this -

Try
' You code which can throw an exception
Catch
' Control comes here when an exception occurs in the try
Finally
' clean up job here
End Try

The Try block contains the code, which can through the exception. If an exception occurs, you handle on Catch block. Finally block is optional and useful when you need to do some clean up job like freeing resources.

1.9 Difference: VB.NET and VB 6.0

Besides above discussed changes in VB language, there are some changes in language syntaxes. All these language and syntax changes are documented in MSDN documentation but I'll still take a quick look.

Data Types Changes

VB.NET introduces a number of data type changes. See table for changed data types and comparison between Vb.NET and VB 6.0.

DataType VB 6.0 VB.NET
Integer 16 bit size 32 bit size
Long 32 bit size 64 bit size
Currency Currency was used to store large floating point values. Replaced with decimal, supports more precision.
Variant Can hold any type of data. Replaced with Object type. Can hold any type of data. Provide better results.
Date Date used to store as double. Introduces DateTime data type designed to store date in different formats.

In VB.NET, Sort data type is 16 bit. In VB.NET, Sort, Integer, and Long are equivalent to CLR's System.Int16, System, Int32, and System.Int64 data types.

Variable Declarations Changes

In VB 6.0, there were many limitations in variable declarations. One of them was can't declare more than one variables in same line. If you did, you had to define data type for each variable or it defaults to Variant data type.

Dim a1, a2 As Integer
Dim a3 As Integer, a4 As Integer

In first line, a1 is a variant type and a2 is an integer data type. In second line, both variables are of type integer.

VB.NET supports multiple variable declarations in the same line. For example,

Dim a1, a2 ,a3 As Integer

Variable initialization was another problem. You can't initialize variable in the same like it is declared. VB.NET support this and now you can initialize variables as you do in C++ or Java.

Dim name As String = "Mahesh"
System.Console.Write(name)

Declaring Constants is straight forward.

Const DT_COUNT As Integer = 23

New Keyword. In VB 6.0, the New keyword is used to create objects. Since data types are an object, so new keyword is used to create a data type object.

Dim i As Integer = New Integer()
i = 10
System.Console.WriteLine(i.ToString())

Block Level Support. Like C++, VB.NET supports block level scope. Declared variables within a block will have scope within the block itself.

For i = 1 To 10
Dim p As Long
System.Console.WriteLine(i.ToString())
Next
System.Console.WriteLine(p.ToString())

In VB.NET, this code will give a compilation error because "p" is not available outside of the For..Next block, which was valid in VB 6.0.

Improved Type Safety

In VB 6.0, you can specify As Any for any type of argument with the declare statement when you declare a reference to an external procedure As Any keywords disable type checking and allow any data type to be passed in or returned.

VB.NET does not support the Any keyword. You must specifically declare the data type of every argument and of the return.

Arrays

There have been significant changes in arrays in VB.NET.

Array Bounds: In VB.NET, first change you'll notice is array bound. In VB 6.0, default lower bound of an array is 0. At 0 lower bound, the number of elements in the array is equal to the upper bound plus one. This statement has 11 elements in the array from A[0] ..A[10]

Dim A(10) Dim Single

You use Option Base to change the lower bound of array to 1.
In VB.NET, Arrays are like C++, the lower bound of every array dimension is 0. Option Base is not supported.

Note: MSDN documentation says that array can have same number of elements as its size. For example,

Dim A(10) As Integer

Can only have 10 elements starting from A(0) to A(9). But actually when I compiled the below examples, it works fine and it seems the array would have 11 elements starting from 0 to 10.

Dim A(10) As Integer
A(0) = 12
A(2) = 24
A(10) = 23
System.Console.WriteLine(A(0).ToString())
System.Console.WriteLine(A(10).ToString())
System.Console.WriteLine(UBound(A).ToString())
System.Console.WriteLine(LBound(A).ToString())

The LBound and UBound in the Listing returns 0 and 10.

ReDim and Fixed Arrays: In VB 6.0, you can specify fixed size arrays.

Dim ArrWeekDays(0 To 6) As Integer

Here ArrWeekDays array is fixes and you can't change it with the ReDim statement.
VB.NET doesn't support fixed size arrays. And ReDim will always work.
You can declare following array in two ways:

Dim ArrWeekDays(6) As Integer
Dim
ArrWeekDays() As Integer = {1, 2, 3, 4, 5, 6}

ReDim Statement: In VB 6.0, ReDim is used to use for initial declaration of a dynamic array. In VB.NET, you can't use it as declaration. You can only use it to change the size of an array but can't change the dimension of an array.

Variant Vs. Object

In VB 6.0, Variant data type can store data of any type in a variable of type Variant. In VB.NET, Object can be used to hold data of any type.

Arithmetic Operators

VB.NET now supports C++ like shortcut operators. The following table shows tow of them. You can use same shortcuts for any operator such as *, /, |, and &.

Operation Syntax Shortcut
Addition A = A+5 A +=5
Subtraction A = A - 5 A -= 5

Fixed Length Strings

In VB 6.0, you can have a fixed length string by specify the length of a string in its declaration. VB.NET doesn't support fixed length strings any more.

Boolean Operators

In VB 6.0, And, Or, Not, or Xor statements were bit level operators but in VB.NET, they are Boolean. The result of these operators returns true or false now. VB.NET introduces new operators to get bitwise results.

Operator Description
BitAnd Bitwise And
BitOr  Bitwose Or
BitXor Bitwise Xor
BitNot Bitwise Not

Structures and User-Defined Types

In VB 6.0, you use Type, End Type to create a structure or user-defined types. For example:

Type StdRec
StdId As Integer
StdName As String
End Type

VB.NET introduces new syntax structure and Type, End Type is not supported any more. The Structure ... End Structure is similar to C++ . You can specify the access scope of every member of the structure, which can be Public, Protected, Friend, Protected Friend, or Private. For example:

Structure StdRec
Public StdId As Integer
Public StdName As String
Private StdInternal As String
End Structure

Structures in VB.NET are like classes, which can have methods and properties as well.

New and Nothing Keywords

In VB 6.0, As New and Nothing keywords are used to declare an object and initializes the object.

In VB.NET, there is no implicit object creation. As we discussed earlier, even data types in VB.NET are objects. So you can create a data type or any object in the following two ways:

Dim i As Integer
Dim i As Integer = New Integer() 
' Do something
if i = Nothing Then
End If

No Support for Set Statement.VB 6.0 you can use Set statement to assign objects. For example:

Set myObj = new MyObject
Set a = b

In VB.NET, you can assign objects without Set keyword. For example:

myObj = new MyObj()
a = b

Changes in Procedure Syntax

There are many changes in procedure syntaxes in VB.NET. These changes are C++ like procedure calls; ByVal is default type, Optional parameter, and return statement.

C++ like Procedure Calls

VB 6.0 allows you to call procedures (sub) with no parentheses with no Call statement. You need to provide parentheses if you're calling a function or a sub with Call statement. For example:

Dim I as Integer
Call
EvaluateData(2, i)
EvaluateData 2, i

In VB.NET, all method calls require parentheses. Call statement is optional.
ByVal is default Argument Type.

In VB 6.0, ByRef was default type when you call a function or sub. That means all changes would reflect in the variable you pass to a parameter. This behavior is changed in VB.NET. Now the default argument type is ByVal. If you don't specify the argument type, compiler takes it as ByVal.

Optional Keyword

In VB 6.0, the Optional keyword is used to give you an option if you want to pass a default value and later you can the IsMissing function to determine whether the argument is present.

Vb.NET, every optional argument must declare a default value and there is no need of IsMissing function. Foe example:

Sub MyMethod(Optional ByVal i As Integer = 3)
Return Statement

Return statement in VB.NET works as C++. You can use Return statement to return the control from a procedure to the calling procedure. In VB 6.0, you can use the Return statement with GoSub statement. The GoSub statement is not supported in VB.NET any more.

Changes in Control Flow Statements

There are following changes in the control flow statements in VB.NET.

  1. GoSub is not supported.
  2. Call, Function, and Sub statements can be used to call prodecures.
  3. In VB.NET, On ... GoSub and On ... GoTo statements are not supported. You can Select Case statement.
  4. The While ... Wend statement has updated While, End While statement. Wend keyword is not supported.

Summary

Visual Basic .NET is the .NET version of Visual Basic. In this article you learned the basics of Visual Basic .Net and you saw the major changes in VB.NET from a VB 6.0 developer's perspective.

In this article, I discussed VB.NET topics briefly. Hopefully, in next series of articles, I will cover these topics in more depth.

share this article :
post comment
 

I can not creat database with databasefactory method of enterprise library

Posted by aditi aditi Oct 16, 2007

I can not creat database with databasefactory method of enterprise library

Posted by aditi aditi Oct 16, 2007

I can not creat database with databasefactory method of enterprise library

Posted by aditi aditi Oct 16, 2007
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor