1

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

Community
  • 1
  • 1
Mech_Engineer
  • 535
  • 1
  • 19
  • 46
  • If you know the type, you can use [CType](https://msdn.microsoft.com/en-us/library/4x2877xb.aspx). CType(theList(0), Body_Cylinder).Segments = 0 – the_lotus Mar 18 '16 at 13:18
  • The link refers to boxing which is slightly different than you want. Since the base has an itemtype property use that to know which it is, then `CType` to convert. – Ňɏssa Pøngjǣrdenlarp Mar 18 '16 at 13:35

1 Answers1

0

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 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks for the reply, but not exactly what I am looking for, I know exactly what object I need to convert from the baseclass to the deriverd class. I want to do this so I can open load this object its property values into a form with textboxes. – Mech_Engineer Mar 18 '16 at 13:20
  • @Mech_Engineer: if you already know it, why don't you cast it? Either with `CType` or `DirectCast`. – Tim Schmelter Mar 18 '16 at 13:24