Av rating:
Total votes: 12
Total comments: 5


Amirthalingam Prasanna
Visual Basic.NET 2005
06 May 2005

New features in Visual Basic.NET 2005
build on platform’s power and efficiency

Although Microsoft.NET languages have more or less the same facilities and power, one must be aware of the syntax and capabilities of a language to take full advantage of it. This article introduces new features of the upcoming Visual Basic.NET language that is part of Visual Studio.NET 2005.

Visual Basic is one of the most popular languages used in the software development industry. Its popularity comes from simplicity and efficiency. The new version of Visual Basic.NET builds upon these attributes and introduces the following useful new features:

  • my namespace
  • partial classes
  • generics
  • operator overloading
  • using block

My namespace

The My namespace feature includes functions and properties to do a lot of complex things in a rapid manner. Think of this as shortcut syntax to get things done with less code. It groups commonly required information and functionalities for easier access. The examples below show how My namespace retrieves the current culture of the application compared to VB.NET 2003:

VB.NET 2003 Code:

System.Threading.Thread.CurrentThread.CurrentCulture

VB.NET 2005 Code:

My.Application.CurrentCulture

Even actions such as accessing various properties of the computer can be done easily and quickly with My namespace. The following code, for example, will return a boolean indicating the availability of the network:

My.Computer.Network.IsAvailable

Partial classes

Partial classes define a class in multiple files. This separation is useful when you want to have functionality of a class coded with different concerns and using inheritance might not be appropriate.

Partial classes are used in Visual Studio.NET 2005 for auto-generated code. When you create a windows form, for example, the Visual Studio.NET 2005 IDE creates a lot of auto-generated code. In previous versions, this code is wrapped in regions in the same source file as event-handling code. In Visual Studio.NET 2005, auto-generated code is separated from event-handling code by defining it in a separate source file as a partial class. Here’s an example of how a partial class can be defined:

Partial Public Class Person
Private pName As String
Private pAge As Integer
End Class

The above definition defines a class with the keyword "Partial" indicating that the definition of the class is split into multiple source files.

Partial Public Class Person
Public Property Name() As String
Get
Return Me.pName
End Get
Set(ByVal value As String)
Me.pName = value
End Set
End Property
Public Property Age() As Integer
Get
Return Me.pAge
End Get
Set(ByVal value As Integer)
Me.pAge = value
End Set
End Property
End Class

Now we are providing more definition of our Person class in a separate source file, providing properties to expose our private fields.

Partial class can also be used to make your datasets more intelligent. The typed datasets you create in Visual Studio.NET have the partial class definition for the generated source. This enables you to add value to your typed dataset by providing functionality such as business logic by defining a partial class definition for the generated class.

Generics

Generics enable your program to adapt itself to different types. The concept of generics is used in the implementation of collections in the new framework. Let’s define a simple customer class as follows:

Public Class Customer
Private name As String
Sub New(ByVal value As String)
Me.name = value
End Sub
End Class

If we want to manipulate a collection of customer objects, a typical implementation in VB.NET 2003 would be:

Dim col As New Collections.ArrayList
col.Add(New Customer("John"))
col.Add(New Customer("Smith"))
col.Add("A String")
'We want our collection to have only Customers
'but still cannot restrict the above line

The problem with this implementation is even though you wanted your collection to only handle customers, there is no way of enforcing this. To restrict your collection to handle only customers, you will need to implement a custom collection class by extending the facilities provided by the collection framework. But what if you want to implement different collections to handle different types of objects? You might end up with a lot of custom collections to handle different types of objects even though the functionality you require from these collections is the same.

This is where generics come in. They give you a way to implement a placeholder for the type and then specify what the type is. An ideal solution to the previous problem would be to provide the implementation of the collection with the type of the collection as a variable; when creating a collection we would specify what the collection should manipulate. That’s exactly the functionality of the collections provided by the System.Collections.Generic namespace in Visual Basic.NET 2005:

Dim col As New Collections.Generic.List(Of Customer)
col.Add(New Customer("John"))
col.Add(New Customer("Smith"))

If you try to add a string or anything other than customer objects, the compiler will detect it as a syntax error. You can also define your own generic functionality to program to types that are not known in advance or to enable your program to work with multiple types.

Public Class GenericClass(Of T)
Public Sub Accept(ByVal val As T)
End Sub
End Class

The above class is defined by using the variable "T" as a placeholder. When you create an instance of GenericClass you replace the placeholder type with a real type. Once we do this, our Accept method will accept only arguments of the real type defined while instantiating GenericClass. For example:

Dim strGeneric As GenericClass(Of Customer)
strGeneric.Accept(New Customer("John"))

Operator overloading

Operator overloading enables you to specify what operators such as + or – should do when invoked with objects of classes you define. For example :

Public Class Box
Public Class Box
Private mArea As Integer
Private mWeight As Integer
Public Property Area() As Integer
Get
Return mArea
End Get
Set(ByVal value As Integer)
mArea = value
End Set
End Property
Public Property Weight() As Integer
Get
Return mWeight
End Get
Set(ByVal value As Integer)
mWeight = value
End Set
End Property
Sub New(ByVal area As Integer, ByVal weight As Integer)
mArea = area
mWeight = weight
End Sub

Public Shar ed Operator +(ByVal value1 As Box, ByVal value2 As Box) As Box
Dim val As New Box
val.Area = value1.Area + value2.Area
val.Weight = value1.Weight + value2.Weight
Return val
End Operator


End Class

The above class definition is a simple box with an area and weight as properties. We wanted to provide functionality to add two box objects and return a box with the area and weight as the total of added boxes. We have overloaded the meaning of the + operator to work with Box objects by defining how it should work. We could have defined a new method with a name to achieve this, but using operators for similar operations makes the code more readable and easy to use. To add two box objects, we simply use the + operator in a way similar to adding two numbers:

Dim b As Box = New Box(12, 32) + New Box(15, 19)

Using block

Some objects you create are very resource intensive. So a good practice is to release the resource as soon as you are finished with it. Generally when you create an object inside a method, the object will not be released until the method terminates. But what if you want an easy way to define an object as well as specify the scope of it inside a method? The using block helps you to achieve this:

Using con As New System.Data.SqlClient.SqlConnection
'Other statements using con
End Using

In the above code, the scope of the defined con object will be limited within the using block and will be released as soon as it exits that block.

Rich and rapid

Visual Basic.NET is one of the popular languages in the .NET platform and future versions are making it richer without losing the rapid development approach for which it’s renowned. This article should help users take immediate advantage of new features that will be an integral part of Visual Studio.NET 2005 and the Microsoft.NET 2.0 platform.



This article has been viewed 8139 times.
Amirthalingam Prasanna

Author profile: Amirthalingam Prasanna

Prasanna is a software engineer, technical author and trainer with over 7 years experience in the software development industry. He is a Microsoft MVP in the Visual developer category, a MCT and a MCPD on enterprise application development. You can read his blog at www.prasanna.ws and e-mail him at feedback@prasanna.ws

Search for other articles by Amirthalingam Prasanna

Rate this article:   Avg rating: from a total of 12 votes.


Poor

OK

Good

Great

Must read
 
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: can't find the error
Posted by: Anonymous (not signed in)
Posted on: Tuesday, November 07, 2006 at 10:01 AM
Message: hello,

can anyone help with the code below? When i skip the first sql command, it works fine, but the first command gives a syntax in field definition error and i can't find why
thank you very much in advance

oehT



SQLCommand = "CREATE TABLE DBSettings (REQID int IDENTITY(1,1), DBVersion varchar, UserName varchar, " + _
"Password varchar, CompanyName varchar, StreetAddress varchar, ZipCode varchar, State varchar, " + _
"Country varchar, Phone varchar, Website varchar, Email varchar, FAX varchar)"
Try
Dim SqlDbCommand As New System.Data.OleDb.OleDbCommand(SQLCommand, SqlDb)
If SqlDb.State = ConnectionState.Open Then
SqlDbCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

'facturen table
SQLCommand = "CREATE TABLE Bills (BillNumber int IDENTITY(1,1), PayedBy varchar, PayedTo varchar, DateOfBill date, DueDate date, OtherPartyReference varchar, AmountToPay varchar)"
Try
Dim SqlDbCommand As New System.Data.OleDb.OleDbCommand(SQLCommand, SqlDb)
If SqlDb.State = ConnectionState.Open Then
SqlDbCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
SQLCommand = "CREATE UNIQUE INDEX BillIndex ON Bills (Billnumber)"
Try
Dim SqlDbCommand As New System.Data.OleDb.OleDbCommand(SQLCommand, SqlDb)
If SqlDb.State = ConnectionState.Open Then
SqlDbCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

Subject: Hello
Posted by: Anonymous (not signed in)
Posted on: Wednesday, May 30, 2007 at 12:23 AM
Message: The code should be :

SQLCommand = "CREATE TABLE DBSettings (REQID int IDENTITY(1,1), DBVersion varchar(50), UserName varchar(50), " + _
"Password varchar(50), CompanyName varchar(50), StreetAddress varchar(50), ZipCode varchar(50), State varchar(50), " + _
"Country varchar(50), Phone varchar(50), Website varchar(50), Email varchar(50), FAX varchar(50))"

Subject: how to settle it???
Posted by: Anonymous (not signed in)
Posted on: Tuesday, July 08, 2008 at 8:16 PM
Message: Hello Dude;
help me to settle this program,because it got errors when i executed it yesterday.this is the coding that i've been try to execute.is it need to include some codes in the Module.vb either?please reply me...thank you for your help,dude. send me ur reply at my fieza_85@hotmail.com..

file name:Demo.vb

Public Class MyFirstLab
Public Class Demo
Public Structure ValueDemo
Public X As Integer

End Structure
Public Class RefDemo
Public Y As Integer

End Class
Public Sub InstantiateTypes()


Dim DemoStructure As ValueDemo

DemoStructure = New ValueDemo

DemoStructure.X = 15

Dim DemoClass As RefDemo

DemoClass = New RefDemo

DemoClass.Y = 15

MsgBox("Hello World!!")
End Sub
End Class
End Class

Subject: how to settle it???
Posted by: Anonymous (not signed in)
Posted on: Tuesday, July 08, 2008 at 8:20 PM
Message: Hello Dude;
help me to settle this program,because it got errors when i executed it yesterday.this is the coding that i've been try to execute.is it need to include some codes in the Module.vb either?please reply me...thank you for your help,dude. send me ur reply at my fieza_85@hotmail.com..

file name:Demo.vb

Public Class MyFirstLab
Public Class Demo
Public Structure ValueDemo
Public X As Integer

End Structure
Public Class RefDemo
Public Y As Integer

End Class
Public Sub InstantiateTypes()


Dim DemoStructure As ValueDemo

DemoStructure = New ValueDemo

DemoStructure.X = 15

Dim DemoClass As RefDemo

DemoClass = New RefDemo

DemoClass.Y = 15

MsgBox("Hello World!!")
End Sub
End Class
End Class

Subject: help
Posted by: spayd3r (not signed in)
Posted on: Thursday, July 24, 2008 at 2:29 AM
Message: help me on how to insert values in the database

 






recommended site pinvoke

PInvoke.net is a user-driven wiki which provides .NET developers with native method signatures, so they don't have to spend time writing them from scratch.





Damon Armstrong
Customizing the Login Page in SharePoint 2007
 Damon shows how a few simple steps lead you to being able to include the login form in a consistent look and feel to...  Read more...


ANTS Profiler and the Un-Rest Cure
 After a while, successful applications can get set in their ways. Bart Read and Andrew Hunter decided... Read more...

Silverlight-Speed Loop
 John Bower steps up a gear, produces a Lamborghini, and examines the process of using a high-speed... Read more...

Sid: Vicious
 Dan Archer documents his epic struggle with an apparently simple task of authenticating user... Read more...

Embedding Help so it will be used
 It is not good enough to make assumptions about the way that users go about getting help when they use... Read more...

Optimising a High-Performance Computing Tool
 Many computer systems nowadays have their ‘correctness’ checked using sample testing, but this isn't... Read more...

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

Beginning ASP.NET 2.0
 It seems that there is both excitement and confusion surrounding Master Pages and Themes. A big part of... Read more...

Over 150,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.

Join Simple Talk