0

I have some classes that use inheritance as in
Teacher : Person : Entity : BaseObject
Student : Person : Entity :BaseObject
Company : Entity : BaseObject etc.

The base object has an abstract IEnumerable property called Hierarchy
Entity class implements Hierarchy as new List<Type>() { typeof(Entity) };
Person class implements Hierarchy as new List<Type> { typeof(Person), typeof(Entity)}; etc.

In my db.Save method I am trying to cast the object to each of these types in turn so I can call the correct stored procedure.

        public static void SaveObject(BaseObject obj)
    {
        foreach (var type in obj.Hierarchy) //obj.Hierarchy is   IEnumerable<Type>
        {
            Object o = obj as type;
            //.....
        }
    }

but I get an error 'type is a variable but is used like a type'. Is there any way I can cast my child object to one of its parent types along these lines?

3
  • Does this answer your question? 'casting' with reflection Aug 2, 2020 at 12:32
  • Thanks. The first answer in that link didn't work because my classes don't implement IConvertible. The second answer from @Rafael looked promising but if I change object o = obj as type to dynamic o = cast(type, obj) and step through the code, even though type changes from Person to Entity as expected, o is still a Person not an Entity after that cast.
    – mdicoope
    Aug 2, 2020 at 13:03
  • The penny drops. I've asked the Cast method to convert from type Person to type Entity but o is still of type Person afterwards. On reflection (if you'll pardon the pun) type Person 'IS' an Entity so the cast has actually worked, just not in the way I want. Might have to step back and come at this from another angle.
    – mdicoope
    Aug 2, 2020 at 13:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.