The Object Class

Objects not only bring encapsulation to your programming fingertips, but they are also part of an object hierarchy called an object class. The benefit of a class is that all objects in the class share the same features. (A single object is said to be an instance of the class.)

note

You can create your own objects. By making them part of an existing class, your objects automatically gain, or inherit, many properties, methods, and events from that class.

When you test an object with If TypeOf, Visual Basic returns the object's class. Therefore, the following line of code returns True or False, depending on whether the object named myObj is a part of the CommandButton class:

If TypeOf myObj Is CommandButton ' Check the class

tip

Visual Basic also supports the TypeOf() function, which returns the class name. For example, TypeOf(myObj) might return CommandButton or Form.

Classes make programming with objects more flexible than would be possible without the class structure. For example, the With...End With statement lets you easily assign multiple properties for a single object. Notice the following code's redundancy:

    chkMaster.Caption = "Primary Source"
    chkMaster.Alignment = vbLeftJustify
    chkMaster.Enabled = True
    chkMaster.Font.Bold = False
    chkMaster.Left = 1000
    chkMaster.RightToLeft = False
    chkMaster.Top = 400
         

When you enclose an object inside a With...End With block, you can eliminate the repetition of the object name. The following code is identical to the previous code:

    With chkMaster
    .Caption = "Primary Source"
    .Alignment = vbLeftJustify
    .Enabled = True
    .Font.Bold = False
    .Left = 1000
    .RightToLeft = False
    .Top = 400
    End With
    

note

Using With...End With for two or three property settings requires more typing than using straight assignments. When you need to assign more than three properties, however, the With clause is an appealing coding statement, because it requires less typing and is easier to maintain if you add properties and require more assignments later.

tip

If you think you'll set additional properties in future versions of the program, you may want to go ahead and use the With clause with only one or two properties.

Top Home