I have several classes, that all derives from SuperClass.
When the classes are created, they all are put into a List(Of SuperClass).
When I go through the list, i would like to downcast the SuperClass object to its baseObject, and put it into the correct list. (I have one list created for each of the sub types of SuperClass).
It is possible to determin:
If TypeOf SuperClass Is SubClass Then
listOfSubClass.Add(DirectCast(SuperCLass, SubClass)
End If
but this is a lot of work, when there are several classes.
By using
SuperClass.GetType.FullName
I get the type of the subClass.
My question is: Is it possible to use this to dynamically cast the SuperClass object?
in psudoCode:
For each SuperClass
Dim temp As SuperClass.GetType.FullName = _
DirectCast(SuperCLass, SuperClass.GetType.FullName
list.add(temp)
Next
Edit:
I was hoping I could use a variable instead of the creating one case for each SubClass and do it all in one loop.
Have you considered using LINQ’s OfType extension method? It wraps an enumerable and filters the elements so that only the ones of the specified type are returned. You could use it like this:
or even:
Sorry if my syntax is off, it’s been a while since I’ve used VB.NET
Edit: Example, as promised:
Another Edit: You could also combine the methods like this:
Don’t forget to add error handling!