Generic Objects (ControlFormScreen)

Generic Objects (Control/Form/Screen)

Generic objects are a form of soft binding (discussed in Chapter 4). A problem arises when you use methods such as ActiveForm or ActiveControl that return object types (Form or Control) that you use as though they were a more specific type. For example, suppose that you have created a form in your application. If you add a TextBox to that form (call it Text1), you have a distinct class derived from the Form object with a property (Text1) that does not exist in the parent Form class.

When you call the method ActiveForm, it returns a Form object that does not have a Text1 property. In Visual Basic 6, you can use that strongly typed object in a late-bound fashion:

Screen.ActiveForm.Text1.Text = "This is a test"

Visual Basic 6 allows you to access the properties and methods of these objects. Visual Basic .NET, on the other hand, has more strict type requirements. While it allows both early and late binding, soft binding is no longer supported. When you upgrade this kind of code, you need to cast the result from ActiveForm to either an object (forcing late binding) or to the specific class that contains the method or property you are attempting to invoke (forcing early binding). The upgraded code can take one of the following forms:

' Forcing late binding by casting to Object CType(ActiveForm, Object).Text1.Text = "This is a test" ' Forcing early binding by casting to Form1 CType(ActiveForm, Form1).Text1.Text = "This is a test"

Although it is up to you to decide what form you prefer, we recommend that you use early binding whenever possible. There is nothing intrinsically wrong with using late binding, but early binding provides the developer with a level of compile-time validation. Late binding can result in errors that are exposed only at run time. It is also slower than early binding because the run-time environment has to bind the methods and properties to the object at run time (hence the term late binding). In an informal test, early-bound property access was more than five times faster than late-bound access. (See the Visual Basic .NET project LateBinding Performance on the companion CD. As you run it, watch the Output window in the debugger.) Why make life more difficult for yourself when you can have the best of both worlds? Early binding is best, unless there is no feasible alternative.



Upgrading Microsoft Visual Basic 6.0to Microsoft Visual Basic  .NET
Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET w/accompanying CD-ROM
ISBN: 073561587X
EAN: 2147483647
Year: 2001
Pages: 179

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net