Search code examples
vb.netlistcastingderived-class

Cast object back to original type


I have objects in a List(of BodyComponent) the BodyComponent is a baseclass, The items beeing added into the list are objects from a derived class.

Public Class Body_Cylinder

' Get the base properties
Inherits BodyComponent

' Set new properties that are only required for cylinders
Public Property Segments() As Integer
Public Property LW_Orientation() As Double End Class

Now I would like to convert the object back to it's original class Body_Cylinder So the user can enter some class specific values for the object.

But I don't know how to do this operation, I looked for some related posts but these are all written in c# of which I don't have any knowledge.

I think the answer might be here but .. can't read it Link


Solution

  • You could use the Enumerable.OfType- LINQ method:

    Dim cylinders = bodyComponentList.OfType(Of Body_Cylinder)()
    For Each cylinder In cylinders
        '  set the properties here '
    Next
    

    The list could contain other types which inherit from BodyComponent.

    So OfType does three things:

    1. checks whether the object is of type Body_Cylinder and
    2. filters all out which are not of that type and
    3. casts it to it. So you can safely use the properties in the loop.

    If you already know the object, why don't you simply cast it? Either with CType or DirectCast.

    Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder)
    

    If you need to pre-check the type you can either use the TypeOf-

    If TypeOf bodyComponentList(0) Is Body_Cylinder Then
        Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder)
    End If
    

    or the TryCast operator:

    Dim cylinder As Body_Cylinder = TryCast(bodyComponentList(0), Body_Cylinder)
    If cylinder IsNot Nothing Then
        ' safe to use properties of Body_Cylinder '
    End If