Question Base Class Collection with Sub Class objects

VentureFree

Well-known member
Joined
Jan 9, 2008
Messages
54
Programming Experience
5-10
I've got some code that I copied from someone else and I'm having trouble making it work that way that I want.

In essence I've got a collection (i.e. it inherits CollectionBase) for a class that acts as a base class for other classes and I can't seem to validate it properly. The problem is in the OnValidate method:
VB.NET:
Protected Overrides Sub OnValidate(ByVal value As Object)
    ' The following was copied from elsewhere, so I'm not sure that I'm using it properly
    If (Not value.GetType() Is Type.GetType("EventBase")) Then
        Throw New ArgumentException("value must be of type EventBase.")
    End If
End Sub 'OnValidate
The reason that this is a problem is that this is a collection of EventBase objects, but I'm trying to populate it with child classes instead. For example, I might have a JumpEvent class that inherits EventBase, and this is being put into the EventBaseCollection. That means that value.GetType() returns the type of JumpEvent, which as you might guess does not equal the type of EventBase.

The goal of course is to simply loop through all of the various events without having to know anything about the sub-classes. Is there a way to determine the type of the base class so that the OnValidate call will work? Or is this just the wrong way to go about it altogether? Thanks.
 
Use Type.GetType(EventBase) not Type.GetType("EventBase") - where EventBase is the name of the base class you are using.
 
Back
Top