Search code examples
c#inheritancecasting

Convert Derived Class to Base Generic Class


I have a set up approximately like this:

public class A { ... }
public class A<T> : A { ... }
public class B<T> : A<T> { ... }
public class C : B<SomeType> { ... }

I am iterating over a list of type A, and I want to check if something is of type B, and if it is, convert it to... B... I can see how it already poses a problem of how am I gonna get the type... but if I cannot do that, what are my other alternatives?

EDIT: To clarify, B contains a method I'd like to use that A does not contain as it simply has no need for it... I want to check which of the objects on that list are of type B so that I can run this method on them

EDIT 2: I forgot to mention the A in the middle earlier... sorry for the confusion


Solution

  • I want to check which of the objects on that list are of type B

    Then introduce a type B into your type hierarchy. Currently you don't have a type B, you've got B<SomeType> which is a different type. so

    public class A { ... }
    
    public abstract class B : A { ... }
    
    public class B<T> : B { ... }
    
    public class C : B<SomeType> { ... }
    

    Or declare the method you want on an interface

    public class A { ... }
    public class A<T> : A { ... }
    public interface IB
    public class B<T> : A<T>, IB { ... }
    public class C : B<SomeType> { ... }
    

    Then for any A you can check if it is IB. This is probably the most natural solution since .NET doesn't have multiple inheritance.