……………………………………………….Expertise in .NET Technologies

Defining Classes in VB.NET

Posted by Ravi Varma Thumati on March 24, 2009

This walkthrough demonstrates how to use class modules to define classes, from which you can then create objects. It also shows you how to create properties and methods for the new class, and demonstrates how objects are initialized.

To define a class

1.      Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project dialog box appears.

2.      Select Windows Application from the list of Visual Basic project templates. The new project is displayed.

3.      Add a new class to the project by clicking Add Class on the Project menu. The Add New Item dialog box appears.

4.      Name the new module StateInfo.vb, and then click Open. The code for the new class is displayed:

Public Class StateInfo
End Class

Note   You can use the Visual Studio .NET code editor to add a class to your startup form by typing the Class keyword followed by the name of the new class. The code editor provides a corresponding End Class statement for you.

5.      To simplify access to the registry classes, add an Imports statement to the top of the source code containing the class statement:

Imports Microsoft.Win32

6.      Define three private fields for the class by placing the following code between the Class and End Class statements:

   Private pVal As String ' Holds the LastFile property value.
   Private KeyName As String ' Holds the name of the registry key.
   Private SubKeyName As String ' Holds the name of the subkey.

These three fields are declared as Private, and can be used only from within the class. You can make fields accessible from outside a class by using access modifiers that provide greater access, such as Public.

7.      Define a property for the class by adding the following code:

Public Property LastFile() As String
   Get ' Retrieves the property value.
      Return pVal
   End Get
   Set(ByVal Value As String)
      pVal = Value
   End Set
End Property

8.      Define methods for the class by adding the following code:

Sub SaveStateInfo()
'  Save the current value of the LastFile property to the registry.
   Dim aKey As RegistryKey
'  Create a key if it does not exist.
   aKey = Registry.CurrentUser.CreateSubKey(KeyName)
'  Save the property value to the registry.
   aKey.SetValue(SubKeyName, pVal)
End Sub
Sub GetStateInfo()
'  Restore the property value LastFile from the 
'  value stored in the registry.
   Dim aKey As Object
   Dim myRegKey As RegistryKey = Registry.CurrentUser
'  This call goes to the Catch block if the registry key is not set.
   myRegKey = myRegKey.OpenSubKey(KeyName)
      Dim oValue As Object = myRegKey.GetValue(SubKeyName)
         pVal = CStr(oValue)
      pVal = "" ' Set to default if key value cannot be read.
   End Try
End Sub

9.      Define a parameterized constructor for the new class by adding a procedure named Sub New:

Sub New(ByVal RegistryKeyName As String, _
        ByVal RegistrySubKeyName As String)
'  Save the names of the registry key and subkey in two fields.
   KeyName = RegistryKeyName
   SubKeyName = RegistrySubKeyName
'  Restore the value of the LastFile property from the registry.
End Sub

The Sub New constructor is called automatically when an object based on this class is created. This constructor sets the value of the fields that hold the registry key and subkey names, and calls a procedure that restores the value of the LastFile property from the registry.

Note   This walkthrough uses the registry to store state information for the class. Information stored in the registry is available to other applications and users, and therefore it should not be used to store security, or critical application information.

10.  Define a Finalize destructor for the class by adding a procedure called Finalize:

Protected Overrides Sub Finalize()
'  Save the value of the LastFile property to the registry
'  when the class loses scope.
   MyBase.Finalize() ' Call Finalize on the base class.
End Sub

The Finalize destructor saves the value stored in the property to the registry after the class loses scope.

To create a button to test the class

1.      Change the startup form to design mode by right-clicking its name in the Solution Explorer, and then clicking View Designer. The startup form for Windows Application projects is named Form1.vb by default. The main form appears.

2.      Add a button to the main form and double-click it to display the code for the Button1_Click event handler. Add the following code to call the test procedure:

'  Create an instance of the class and pass the registry key
'  names to the Sub New constructor.
   Dim SI As New StateInfo("SoftwareStateInfo", "PropertyValue")
'  Display the value of the property if it has been restored.
   If Len(SI.LastFile) > 1 Then
      MsgBox("The value of the property LastFile is: " _
             & SI.LastFile)
      MsgBox("The LastFile property has not been set.")
   End If
   SI.LastFile = "C:BinaryFile.txt" ' Set the property.
'  Ask the object to save the property value to the registry.

To run your application

1.      Run your application by pressing F5. The application appears.

2.      Click the button on the form to call the test procedure. The first time you do so, a message is displayed stating that the LastFile property has not been set.

3.      Click OK to dismiss the message box. The Button1_Click procedure sets the value of the LastFile property and calls the SaveState method. Even if SaveState were not called explicitly from Button1_Click, it would be called automatically by the Finalize method after the startup form is closed.

4.      Click the button a second time. The message “The value of the property LastFile is C:BinaryFile.txt” is displayed.

5.      Close the main form and then restart the program by pressing F5. An object based on the class is created, and its Sub New constructor calls the GetStateInfo procedure that restores the property value from the registry. The message “The value of the property LastFile is C:BinaryFile.txt” is displayed again when you click the button.


3 Responses to “Defining Classes in VB.NET”

  1. Hey – nice weblog, simply wanting around some blogs, seems a pretty good platform You Are using. I’m presently utilizing Drupal for a few of my websites but looking to change one among them over to a platform very much the same to yours as a trial run. Anything in particular you’d recommend about it?

  2. Really like your websites particulars! Undoubtedly an exquisite provide of information that is extraordinarily helpful. Stick with it to hold publishing and that i’m gonna proceed studying by way of! Cheers.

  3. Well that was a good read.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: