Find an object of a given type


I'm in an odd situation. I have a horrendous number of classes that derive from each other and I store objects in various collections.

So for example:

Record <-- CostRecord <-- AccruedCostRecord
                      <-- PrepaidCostRecord
                      <-- StockRecord

The objects are stored in a List(Of Record) and I want to search a particular list for a record of a given type.

    Private Function findRecord(listToSearch As List(of Record), recordName As String, recordType As Type) As Record
        For i As Integer = 0 To listToSearch.Count - 1
            If listToSearch(i).name.equals(recordName)
                'If record is of type "recordType" then return it
            End If
    End Function

Normally I would use the "TypeOf ... Is" operator as I am interested in the base class types too. So if I passed in "CostRecord" I would expect to retrieve a AccruedCostRecord, PrepaidCostRecord or StockRecord.

In this case I can't use TypeOf because it doesn't accept System.Type as an argument and I can't think of another way of telling it what I want.

I don't believe that "GetType" is going to help me here either because I'm interested in base classes.

Has anyone any ideas? Perhaps some kind of crazy Reflection magic?


You can use the method .IsAssignableFrom on your type:

If recordType.IsAssignableFrom(listToSearch(i).GetType())

For example, if your list item is AccruedCostRecord and your recordType is CostRecord, this will return True.