Discovering Type Information at Runtime

There will be many instances when you need to discover type information without writing weakly typed code. As shown in the last section, we can use the sender argument of an event handler to obtain properties from the object that raised an event. Type information is literally defined by a class named Type , defined in the System namespace.

To some extent, talking about Reflection and talking about the Type class go hand in hand. There are too many members in the Type class to list here, so I won't do it. I will tell you that all the information is available in the integrated help documentation, and you can discover just about anything you want to about a type by requesting an object's type information. The easiest way to request type information is to invoke GetType . For example, Button1.GetType returns the Type object for Button1 .

In the preceding section we simply cast sender to a control with CType(sender, Control) . You will not want to do that in a robust application. The sender parameter can be anything. We could add a sentinel to Listing 4.2. If the type of the sender parameter is not the type we are interested in ”a control ”then we can exit the subroutine. The following statement demonstrates how to check the type of an object.

 If Not (TypeOf sender Is Control) Then Return 


Use a list of sentinels to avoid nested or complicated If conditional logic.


Some people like to write positive If conditional statements that perform a positive condition test. For example, If condition Then perform some code . This was actually taught at the university I attended, Michigan State University. I prefer to write a sentinel. A sentinel is code that acts as a guard condition, like the challenge, "Halt! What is the password?" If you don't know the password, you are not admitted. A sentinel checks the negative condition and exits if the test fails. We can write the code as If Not condition Then Return .

The TypeOf keyword gets the type information of the first parameter and checks to see if its type is the same as the operand on the right-hand side of the Is keyword. Thus we understand the preceding code statement to mean, "If sender 's type is not a control, exit the subroutine." To paraphrase Francis Bacon, "Princes to keep due sentinel."

Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel © 2008-2017.
If you may any questions please contact us: