locked
Downcast (More like Convert) to Base Type RRS feed

  • Question

  • User-180718643 posted

    Hi all,

    Is there a way to truly convert a child object to a base type... Let say I have the following classes:

    Base Class: Pet

    Child Class: Cat

    Child Class: Dog

    How do I convert Dog to a Pet? I can Ctype(Dog, Pet), but if you do a "GetType", Ctype(Dog, Pet) will still return "Dog" as the data type.

    I don't mind during the downcasting process that I lose the dog specific properties, etc.

    Any ideas?

    Thanks.
     

    Thursday, May 29, 2008 10:35 PM

All replies

  • User-989915499 posted

    Hi There,

    Why do you wanted to get the base type for as your child can perform everything that base can do.

    If you just wanted to get the name of base:

    Dim name as String = myDog.GetType().BaseType().Name

    Hope it helps!

    Friday, May 30, 2008 12:04 AM
  • User-180718643 posted

    I have a situation with Generics ... and I think I may have confused the issue. Here is what I have:

     

    Base Class Pet

    Base Collection Class PetCollection(of T as {Pet}) Inherits List(Of Pet)

    Child Class Cat 

    Child Class Cats Inierits PetCollection(of Cat)

    Child Class Dog 

    Child Class Dogs Inierits PetCollection(of Dog)

    etc.

     
    I have a function which I want to do the following 

    Public Class MyHelperClass(Of T as {Pet})
        Public Function CreateList(Byval InputListOfAnotherCollection as Array) as PetCollection(Of T)
    End Class
     

    What I want to do is go:

     

    Cats = CreateList(MyArray)

     
    However, PetCollection(Of T) can't be cast to Cats.

     
    Actually I think this might be an upcoversion issue not a downconversion.
     

    Friday, May 30, 2008 11:25 AM
  • User1788825812 posted

    When you instantiate an object it always remains the original type you created. In your first post you did GetType after you cast the object to the parent class. It is correct that the type will remain Cat or Dog and not Pet. However once it is cast to Pet you will only be able to access the Cat or Dog object through the Pet interface. So if you have implemented extra methods or properties in Cat or Dog they will not be visible while the object is cast as a Pet but they will become visible again once the object is cast back to Cat or Dog.

    I think this is important for the problem you are having in your second post. A Pet can not be cast to a Cat or Dog type if the underlying object is a Pet object that was created by new Pet. This of course applies to the collection classes as well.


    Monday, June 9, 2008 7:17 AM