Events with class declared as objects

CJLeit

Freshman
Joined
Feb 1, 2006
Messages
32
Below is a sample of some code I am working with. I need to be able to declare a class as a generic object because I will load a different class based on some user selection. The code works OK but I wondering if there is a way to use the AddHandler without having to convert my object every time. If I don't put in the CType I can't compile because it tells me sampleEvent is not an event of 'Object'. I can access all my properties and methods just fine without using the CType each time but not my events. Any suggestions?

Code:
Public obj As Object
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    obj = New Test
    obj = cType(obj, Test)
    AddHandler [B]CType(obj, Test).sampleEvent[/B], AddressOf junk
    obj.sampleProperty = "hello"
End Sub
 
It is generally recommended that you turn on "Option Explicit" and "Option Strict." You are using late binding here (where the function that will be called is determined at runtime based on the type of object), which is an option that does work, but is generally looked down upon because it can allow certain types of errors in your code to go unnoticed. If you absolutely need to use late binding, you should research reflection (which has support for events), but in this case I would actually recommend that you use an interface, which also supports propertites, functions, and events.
 
The only problem I have using an interface is that some of the classes may have properties that are unique to them that I wouldn't include in the intefece. In that case would the following code be the correct way to access those properties?

Thanks!

Code:
Public obj As intTest

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    obj = New Test
    [B]CType(obj, Test).sampleProperty = "hello"[/B]
    AddHandler obj.testEvent, AddressOf testEvent
End Sub
 
If the objects are so different they can't have a consistent interface then you are always going to encounter problems in this kind of situation.

Personally though I would still define relevant Interface(s) where possible and use it (them) rather than just using object as a datatype, if you need to access properties not defined in the interface then you would still need to cast the variable to the correct type - but at least the cast wouldn't be required in as many places.
 
Back
Top