Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Object Oriented features in VB.net (Part-2)

Total Hit ( 11132)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


In the previous article we discussed the basic concepts of Object Oriented Programming. Now let's implement all this in our favorite language - VB.net.

Creating Classes in VB.net

As we discussed earlier, objects are instances of a specific template – called a Class. A "Class" contains the code that defines the behavior of its objects, as well as member variables which can hold data of an object. In VB.net you can use the “Class” keyword to create a class.

Syntax:

Click here to copy the following block
[ <attrlist> ] [ Public | Private | Protected | Friend | Protected Friend ] [ Shadows ] [ MustInherit | NotInheritable ]
Class name
  [ Inherits classname ]
  [ Implements interfacenames ]

  '
  [ statements ]
  '

End Class

For full description of “Class” statement check out this description at MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmClass.asp

Example :

Click here to copy the following block
'//Declaring a “vehicle” class
Public Class Vehicle
   '//some code    
End Class

In VB.net you can create one or more than one classes in a single file (*.vb extension).
In the IDE:
- Create a windows application.
- Click Project->Add Class
- Name your file MyClassFile.vb

The following screenshot displays a sample class file with 4 classes defined.





Object construction (constructor methods)

You can create an object of the Class by using the “New” keyword. As mentioned before, an Object is an instance of a class.

Click here to copy the following block
Dim objV1 as New Vehicle '//Declare a new object and allocate memory

You can also declare a variable and allocate memory at a much later stage, when required.

Click here to copy the following block
Dim objV1 as Vehicle

'... Some code

objV1= New Vehicle  '//Allocate memory

'... Some code

While creating a class you can define a special method called “Constructor”. A Constructor is special because it is invoked automatically when an object is created. In VB.net this special method always named as “New” and can take zero or more arguments as shown below

Click here to copy the following block
Public Class Vehicle
  Private m_VehicleNumber As String               '//private member variable
     
  Sub New()
    '//write object initialization code here
    m_VehicleNumber = ""
  End Sub
End Class

A constructor may also take parameters as shown below:

Parameterized Constructors

Click here to copy the following block
Public Class Vehicle
  Private m_VehicleNumber As String '//private member variable
     
  Sub New(ByVal ViNumber As String)

    '//write object initialization code here

    m_VehicleNumber = ViNumber
  End Sub
End Class

A Class having a parameterized constructor can be very useful if you need to set the value of member variables each time an object is initialized. For example in the “Vehicle” class you can set VehicleNumber when you declare an object.

Click here to copy the following block
Dim objVh As New Vehicle("734 YBD")

A peek at polymorphism:
We can even have multiple definitions of the New() method as long as the number of parameters and/or their datatypes are different. (The number of parameters and the respective datatypes passed to a function or method is called the method’s signature.)

Class with multiple Constructors

Click here to copy the following block
Public Class Vehicle
  Private m_VehicleNumber As String '//private member variable

  '//this constructor doesn’t take any argument
     
  Sub New()
    '//write object initialization code here
    m_VehicleNumber = ""
  End Sub

'//this constructor takes one String argument

  Sub New(ByVal ViNumber As String)
    '//write object initialization code here
    m_VehicleNumber = ViNumber
  End Sub
End Class

The compiler will automatically call the correct constructor depending on data-types and number of arguments passed in the object declaration statement.

We will cover object declaration in much more detail later in this article.


You can also implement a constructor by using the Optional parameter. This lets us pass values if required.

Constructor with optional parameter

Click here to copy the following block
Public Class Vehicle
  Private m_VehicleNumber As String '//private member variable
  
  '//constructor with optional argument
  Sub New(Optional ByVal ViNumber As String=””)
    '[write object initialization code here]
    If ViNumber<>”” Then
        m_VehicleNumber = ViNumber
    End If    
  End Sub
End Class

Let me remind the newbies that a Constructor is an optional method. It is not new concept, it has been there for quite some time. Languages C++, and Java which support object oriented features have constructors. C++ has destructors but not Java.

VB6 had concept similar to a Constructor. It was implemented as Class_Initialize event but didn’t allow passing of parameters.

Termination and Cleanup (Destructors)

We have just seen how constructors work. Now lets look at cleanup of objects. In VB.net you can free object memory using the following statement:

Click here to copy the following block
objV1= Nothing

But again this will only mark an object for garbage collection. Actual memory will be freed only when garbage collection occurs.
Click here to learn more about Garbage Collection.

In VB6 we had Class_Terminate event (Destructor) which fires when all references of an object set to nothing in other words when object reference counter reaches to zero. VB.Net doesn’t have the same mechanism. This is because of the garbage collector’s non-deterministic approach. Generally garbage collection usually occurs in low memory situation.
Here, in VB.Net we can write clean up code in an object’s Finalize method which acts as a destructor.

Click here to copy the following block
Public Class MyTestClass
  '//Cleanup routine which can be called by client application
  Public Sub Dispose()
    Finalize()
  End Sub
  
  '//Clean up routine called by GC
  Protected Overrides Sub Finalize
    '//Your clean up code (i.e. free the database connection,release file locks etc...)

    '//Call base class finalize method explicitly if required
    MyBase.Finalize()    
  End Sub
End Class

Member Variables

Member variables hold data of an object. Each object gets its own copy of member variables. Let us look at an example.

Click here to copy the following block
Public Class MyTestClass
  Const MAX_COUNTER=25
  Private nCounter As Integer
  Public sMessage As String

  Sub New()
    nCounter = 5
  End Sub
    
  Function ShowMessage()
    MsgBox ("Counter is " & nCounter)
  End Function
End Class

Using access modifiers with variables:

When a variable is defined with an access modifier, the modifier influences its availability to other code.
  1. Public – available to code outside our class
  2. Private – available only to code within our class
  3. Friend – available only to code within our project/component 
  4. Protected – available only to classes that inherit from our class 
  5. Protected Friend – available to code within our project/component and classes that inherit from our class whether in our project or not

Note: By "our class", I mean the class in which the variable is declared.
 
Methods

When we create a class, the objects typically need to provide some services. For example, we can have a "Graphics" class which provides methods like DrawLine, DrawCircle etc.

Methods can be defined as Public Private or Protected. This alters the object's Interface. In VB you can create a new method using “Sub” or “Function” keyword. Sub will create a sub-program or a sub-procedure. A Sub-program doesn’t return a value. It can only provide services by executing a set of statements. A "Function" is like a "Sub" but it can return a value (or values) if required.

Let’s take a look at an example of Sub and Function.

Click here to copy the following block
Public Class CGraphics
  Public Sub DrawCircle(ByVal x1 As Integer, ByVal y1 As Integer, ByVal Radius As Integer)
    '/some code to draw circle    
  End Sub

  Public Function CalcCircleArea(ByVal Radius As Integer) As Double
    Const PI = 3.14
    Return PI * (Radius * Radius)
  End Function
End Class

Now that we have declared the methods, here is how we call the methods.

Click here to copy the following block
'/Calling a Sub
Dim myObj as New CGraphics
Dim area as Double

myObj.DrawCircle(100,100, 25)

'/Calling a function
area = CalcCircleArea(25)

Properties

A Property is a special type of method which is designed to assign and retrieve class data. Properties are nothing but wrapper methods on member variables. Each property must contain at least one block of GET or SET. Get method is called when you read property and Set method is called when you assign a value to the property. You can define a private variable and expose them through "Properties". This makes sure that the variables are not set to illegal values or modified in an unauthorized manner. We can restrict values and define some rules for the member variable. Let’s see a typical example of a Class using a Property.

Declaring a simple Read/Write Property

Click here to copy the following block
Public Class CPerson
  Private m_Age As Integer

  Public Property Age() As Integer
    Get
      Return m_Age
    End Get
    Set(ByVal Value As Integer)
      If Value <12 Or Value>18 Then
        Throw (New Exception("Age must be between 12 and 18"))
      Else
        m_Age = Value
      End If
    End Set
  End Property
End Class

In the above example, CPerson class contains one member variable m_Age which is defined as Private and therefore not accessible to code outside the class. We have also declared a Property which can be used to get or set Person's Age. You can define your own logic to control member variable’s value inside the property. Here we have restricted the Age values to between 12 and 18.

How to use Properties?

Its very simple! You can read or write Property just like a normal variable and that’s why it’s very transparent to user who is accessing an object’s member. Here's how to do it:

Click here to copy the following block
Dim obj As New Person
Obj.Age=12 '//set person’s age
Msgbox("Person age is : " & obj.Age) '//read age

Obj.Age=35 '//set age : **** Error **** (Age must be between 12 to18)

Read-Only Properties

There are times when you don’t want user to assign any values to a Property but instead want to make it read only. A Read-Only property only implements Get section of a property.

Example :

Click here to copy the following block
Public Class CPerson
  Private m_Age As Integer

  Public ReadOnly Property Age() As Integer
    Get
      Return m_Age
    End Get    
  End Property
End Class

Write-Only Properties

Just like ReadOnly property you can declare a Write-Only property by implementing only the “Set” section.

Example :

Click here to copy the following block
Public Class CPerson
  Private m_Age As Integer

  Public WriteOnly Property Age() As Integer
    Set(ByVal Value As Integer)
      If Value < 12 Or Value > 18 Then
        Throw (New Exception("Age must be between 12 to 18"))
      Else
        m_Age = Value
      End If
    End Set
  End Property
End Class

Parameterized Properties

This is another useful type of property. You can use single property to access more than one type of values. This is often very useful when you don’t want to declare multiple properties for conceptually same type of member variables or an array of variables which you want to access through property. Here I have included a simple example where array of friend names can be accessed using MyFriends property.

Example :

Click here to copy the following block
Public Class CPerson
  Private m_ColFriends As New Collection

  Public Property MyFriends(ByVal index As Integer) As String
    Get
      Return m_ColFriends(index)
    End Get
    Set(ByVal Friendname As String)
      m_ColFriends.Add(Friendname)
    End Set
  End Property
End Class

How to Useparameterized properties?

Click here to copy the following block
Dim p1 As New CPerson
'//assign values
p1.MyFriends(1) = "Bob"
p1.MyFriends(2) = "Ron"
p1.MyFriends(3) = "Jim"

'//Read values
MsgBox("My first friend is : " & p1.MyFriends(1))
MsgBox("My second friend is : " & p1.MyFriends(2))
MsgBox("My third friend is : " & p1.MyFriends(3))

The Default Property

Also there are times when you want to provide a more easy interface to users so that they can access object’s most frequently used property without writing long code. The Collection type of classes implement this and are good examples of this. For example in when you access collection you don’t have to specify myCol.Item(i) but you can simply write myCol(i). This type of property is known as Default Property. In VB6 you could mark any property as Default but in Vb.net only parameterized properties are allowed to be declared as Default.

Check out this example of a Default property of CPerson class. Here I have declared MyFriends as default property using “Default” keyword.

Example :

Click here to copy the following block
Public Class CPerson
  Private m_ColFriends As New Collection

  Public Property MyFriends(ByVal index As Integer) As String
    Get
      Return m_ColFriends(index)
    End Get
    Set(ByVal Friendname As String)
      m_ColFriends.Add(Friendname)
    End Set
  End Property
End Class

How to Usage default property?

D

Click here to copy the following block
im p1 As New CPerson

'//assign values
p1(1) = "Bob"
p1(2) = "Ron"
p1(3) = "Jim"

'//Read values
MsgBox("My first friend is : " & p1(1))
MsgBox("My second friend is : " & p1(2))
MsgBox("My third friend is : " & p1(3))

Events

Sometimes you might need to inform client code about certain activity from the Class. "Events" are a special mechanism to notify client code from the Class. You can raise events for a certain situation and inform client code so that appropriate action may be taken by client’s code. Very common event examples are Textbox’s TextChanged event, Button’s Click event, Connection’s Close event.

Declaring Events

You can declare event in your class by using “Event” keyword as shown below.

Click here to copy the following block
Public Class CPerson
   Public Event Born() '//event without any parameter
   Public Event Died(ByVal AgeDiedAt as Integer) '//event with one parameter

   '
   ' // Some code
   '
End Class

Raising/Firing Events

You can raise an Event declared with Event keyword in your class. Events can be raised from Sub, Function or Property.

Click here to copy the following block
Public Class CPerson
   Private Age As Integer
    
   Public Event Born() '//event without any parameter
   Public Event Died(ByVal AgeDiedAt as Integer) '//event with one parameter
   
   Public Sub New()
       Age=0
       RaiseEvent Born '//Fire event
   End Sub

   Sub KillMe()
       RaiseEvent Died (Age) '//Fire event
   End Sub
End Class

Receiving events in client code

There are 2 different ways to handle these events:

1. Handling events using “Handles” keyword
2. Using AddHandler method to specify the Event-Handler at runtime

Handling events using “Handles” and “WithEvents” keywords

This is a very common approach to handle object’s events. Most probably you've already seen code like this:

Click here to copy the following block
Private Sub Button1_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles button1.Click
  Msgbox “Button1 Clicked”
End Sub

You can attach one or more than one events to a Sub matching with event signature. When you use “Handles” keyword to attach an event with an event handler, then there is something very important to remember. You must declare your object using "WithEvents" keyword as shown here:

Click here to copy the following block
'//class with event
Public Class CPerson
  Public FirstName As String
  Public Event Killed(ByVal Sender As Object, ByVal ByWhom As String)

  Sub New(ByVal MyName As String)
    FirstName = MyName
  End Sub

  Public Sub Kill(ByVal ByWhom As String)
    RaiseEvent Killed(Me, ByWhom)
  End Sub
End Class


Click here to copy the following block
'//consuming event
'[1] Declare object using WithEvents keyword
Dim WithEvents p1 As New CPerson("Mr. Bean")

'[2] Attach object’s event with event handler using “Handles” keyword
Sub OnPersonKilled(ByVal Sender As Object, ByVal ByWhom As String) Handles p1.Killed
  MsgBox(Sender.FirstName & " was killed by : " & ByWhom)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  p1.Kill("Joe")
End Sub

Handling multiple events using a single event handler

You can handle multiple events using one event handler but there is a condition. The only condition is, all events handled by event handler must have the same signature (i.e. Event arguments and datatypes must be same).

For example you can use one event handler to handle click event from Button1 and checkChanged event from CheckBox1.

Click here to copy the following block
Private Sub OnSomeControlClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, CheckBox1.CheckedChanged
   Msgbox (sender.Name & “ was clicked”)
End Sub

Writing consistent event handling code by following .Net standards.

In all .Net framework class libraries you will see events with only 2 arguments (sender and event info). This makes it easy to write consistent code throughout the project. Here is the description about arguments - sender and event info:

Sender (Base Type System.Object): The object which raised the event
e (Base Type System.EventArgs): More info about the event.

You can always create your own Event Info class derived from System.EventArgs if you want to follow the standard. Few example of inbuilt .Net EventArgs classes are KeyEventArgs, PrintEventArgs, TreeViewEventArgs …

You can create your own EventArgs Class as shown below.
Note: We will see Inheritance in more detail later in this tutorial series.

Click here to copy the following block
Public Class PersonEventArgs
  Inherits EventArgs

  Public ByWhom As String
  '//
  '// Add more event items here    
  '//    
End Class

Dynamic event using AddHandler/RemoveHandler

So far you have learnt that how to create events, raise events and receive events using “Handles” and “WithEvents” keywords.

The above example to handle events using “Handles” keyword can handle the object’s events which are assigned in the list after “Handles” keyword. This approach won't work if you want to assign an event handler to an object at runtime.

So question is how to attach an event with some event handler at runtime? Here is the example which will create a new CPerson object on button click event and attach object’s Killed event with OnPersonKilled event handler. Here is the full code:

Click here to copy the following block
'//class with event
Public Class CPerson
  Public FirstName As String
  Public Event Killed(ByVal Sender As Object, ByVal ByWhom As String)

  Sub New(ByVal MyName As String)
    FirstName = MyName
  End Sub

  Public Sub Kill(ByVal ByWhom As String)
    RaiseEvent Killed(Me, ByWhom)
  End Sub
End Class


Click here to copy the following block
Dim p1, p2, p3 As CPerson '//define objects
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  '//allocate memory for objects
  p1 = New CPerson("Joe")
  p2 = New CPerson("Bob")
  p3 = New CPerson("Kim")

  '//attach object's event with some event handler
  AddHandler p1.Killed, AddressOf OnPersonKilled
  AddHandler p2.Killed, AddressOf OnPersonKilled
  AddHandler p3.Killed, AddressOf OnPersonKilled

  '//Now call kill method
  p1.Kill("SomeEvilPerson")
  p2.Kill("SomeEvilPerson")
  p3.Kill("SomeEvilPerson")

  '//deattach object's event from event handler
  RemoveHandler p1.Killed, AddressOf OnPersonKilled
  RemoveHandler p2.Killed, AddressOf OnPersonKilled
  RemoveHandler p3.Killed, AddressOf OnPersonKilled

End Sub

Private Sub OnPersonKilled(ByVal sender As System.Object, ByVal ByWhom As String)
  '//You can use CType to convert any object to a specified type to get
  '//design time intellisense and convert an object to a specified type.
  MsgBox(CType(sender, CPerson).FirstName & " Was killed by " & ByWhom)
End Sub

So far we have seen how to create your own classes, define members, methods, events and properties. In the next article we will learn about inheritance and some advanced features in VB.net.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.