Microsoft & .NETVisual BasicBeginning Objects in VB - Part 2

Beginning Objects in VB – Part 2 content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Back so soon? Goodness me, I’m finding it hard to keep up with all this object lark.

Anyway, back to reality – in the second part (yes, this is the second part – if you missed the first, then click here) This week we’ll take a look at:

– Creating objects through code
– Registering a component
– Using properties to enhance the SayHello method
– Enhancing the Project1 component

In case you didn’t bother to say anything about the last article (I’ll see you after lessons!), please say what you thought of this part by scrolling to the bottom of this page, or in fact any of the pages in this article, and clicking Post Feedback Now!

Righty ho, lets go!

(You: Terrible rhyme!)
(Me: I know!)

In this day and age, you need to know how to create an object through code. It’s rather like declaring a variable, in fact it is in a sense, but instead of declaring it as a data type (e.g. String), you declare it as an object (in our case, Class1).

You can declare an object using either the Dim, Private or Public keyword. As with other variables, the Private and Public keywords can only be used in the General Declarations procedure.

You will probably know that declaring something as Public allows anyone to access the variable, and declaring it as Private only lets the current module of code access the variable.

Anyway, stop blabbing on!

The sort of variable declaration that you’re used to is something like:

Private m_strName As String

Well, here is a simple object variable declaration:

Private m_clsClass1 As Class1

Easy. But if you remember from the previous part, we used a different piece of code to actually create the code:

Set m_clsProject1 = New Class1

Help!!!! What on earth does this do??

Well, don’t worry, I’m here to hold your hand all the way (ok, so your mouse will have to hold your hand in my absence)

What that line of code does is create a new ‘instance’ of the object Class1. It means that you can now do some stuff with the object, whereas before if you tried doing anything you would have had the following error message:

Object or With Variable Not Set

Don’t you just love VB error messages?

(Me: Well, no actually)
(You: Weren’t you being sarcastic?)
(Me: Good point. DOH!)

Anyway, getting back to the point, you need to actually create a New instance of the object to be able to use it. But if you thought you just had to do it that way every time, then you were wrong….

VB allows you to use the New keyword when you declare an object variable:

Private m_clsClass1 As New Class1

When your program starts, the object is automatically created so you can use its methods etc immediately. This may sound really brill, but let me point out a few probs with it.

If your object fires up a connection a database and gets some records when you start, or if your object simply contains a large amount of code, then you may be causing the users machine to run slower then needed. If you don’t make a call on the object for a few minutes, then you are wasting memory by having the object in memory.

So, what can you do? Well, simply avoid using the New keyword when declaring the object. Every time you want to use it, create a new instance of it and then destroy it (Destroy it? You mean bash my computer over the head?)

No, not quite. When dealing with objects (as we’ll see later on) you use the Set keyword to perform some operations. When we want to destroy an object, we set it to nothing, quite literally:

Set m_clsClass1 = Nothing

This way, we only have it loaded in memory when we need to use it. But, if I take the example used earlier of the database, it may be better to keep the object ‘alive’ as to speak for longer because invoking it several times may be the slower option. It’s really a case of working out which is going to be more efficient.

If you have a lot of users using a database object for example, then you may want to open and close connections for each user. This is called object ‘pooling’ where you pool all your resources together and dish them out when requested. Microsoft makes this easier by giving you Microsoft Transaction Server, but I won’t go into the complicated ins and outs of that beast now.

So, as you can see object dudes, it’s down to you to work out when you need to new object and when you can destroy it.

Next we move onto registering your object…

In the first part of this tutorial, we built our project into a DLL from VB. Now, because VB is nice and cares about its users (yeah right!) it automatically registers the DLL on your machine when you build it. This saves a lot of hassle, but hides the fact that it does that.

So, when you come to distribute your DLL to your friends machine and he complains that it doesn’t work, you haven’t got a clue why.

Each DLL (or component) on your machine has to be registered (including controls). Once registered, an entry in to the registry is made, but I don’t suggest the best route is to dive into the registry and try and do things in there (many a machine has died from that treatment)

How do we do it then? Well, there are several ways. Luckily for you, some guys have already thought about this and put together a nifty little tool which not only allows you to register components, but also to unregister them! So now when you friend gives you his “I am the best programmer in the world” component which flashes up a message box every five seconds saying just that, you can now unregister it!

(Your friend: Time to die Mr Huggill!)

OK. So who are these guys and where can I get this cool tool? Well, they are a bunch of awesome programmers who are part of a project to replace the standard VB controls with better ones, and to provide some handy controls as well. The CCRP (Common Controls Replacement Project) has been around for sometime, and is somewhat a hero amongst many programmers (me included!)

You can visit their web site by: clicking here If you want their registration utility, then look under the Cools Tools page for CCRP Reg Util.

I will quickly take you though using it.

After you have downloaded and unpacked the files, run the exe file ccrpregutil.exe and you will see the following screen:

Click here for a larger image.

Simply click on Specify File, select either a DLL or OCX file and click OK and Register or Unregister (depending on how much you like your friend)

Easy. And, if you want to register your component when you put it in your setup program, don’t worry! The Package & Deployment Wizard that comes with VB does that for you.

Right, enough about registration, lets do some properties!

Carrying on from the super exciting class we made last week, lets take a look at making the SayHello method a bit more user friendly.

Firstly, lets allow the developer using our component to specify the message displayed by the message box (in case they got fed up of Hello World!)

We could just pass the message as an argument in the SayHello method, but that’s not the point I’m trying to make!!

What we will do is to use a property inside the class, which the developer will set, and then call the SayHello method. The property must be public to allow our developer to access it, and we want it to be a string. Add this line of code to the General Declarations procedure of Class1 (if you’ve lost the plot here retrace your steps to the first part by clicking here)

Public Message As String

Simple eh? Good. Lets move on.

We now need to modify the SayHello method to use the Message variable in place of our lovely Hello World! message:

Public Sub SayHello()
    Msgbox Message
End Sub

Still not very dynamic is it? Perhaps we could allow the developer to set some of the attributes of the message box? Like the icon displayed? Great! For this I suggest that we use our own enumeration (“Frank, he said a word!” – No I haven’t just said my first word, but an enum is pretty exciting!)

For demonstration purposes, we are going to use our own public enum (private enums aren’t allowed as arguments) to store the message box icon styles, and have the developer set the icon as an argument in the SayHello method. Here is our enum (add it to the General Declarations procedure)

Public Enum eMsgIcons
    eCritical = 16
    eExclamation = 48
    eInformation = 64
    eQuestion = 32
End Enum

This is cool man!

Now all we need to do is to change the SayHello method a bit:

Public Sub SayHello(Icon As eMsgIcons)
    MsgBox Message, Icon
End Sub

Right! Quickly build the DLL and switch over to our Standard EXE project. Modify the Form_Load procedure to look like this:

Private Sub Form_Load()
    m_clsClass1.Message = "Hello Programmers!"
    m_clsClass1.SayHello eInformation
End Sub

Where’s the Set m_clsClass1 thingy bit gone? Well, I decided that we would create the object as New from the program startup, so modify the General Declarations procedure to look like this:

Private m_clsClass1 As New Class1

Easy! Run the program, and you see a nice popup message box:

All that’s left to do is to destroy the object when we close the program. So add the following code to the Form_Unload() event procedure:

Private Sub Form_Unload()
    Set m_clsClass1 = Nothing
End Sub

And there you have your first (well, actually your second) component program using a combination of methods, properties, enumerations and arguments!

I’ve got to dash now, the next part needs writing! But I’ll see you same time next week for another tasty serving of hardcore object programming!

Quick, download the files before I remember to give the link!
Download the files!

Goodbye World!
– Sam

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories