c# generic inheritance base class to child class


I have the following Base class:

public abstract class BaseClass<T>  where T : IComparable


and this child class :

public class ChildClass<T> : BaseClass<int>


from a diffrent place on the program i have the following code:

  List<BaseClass<IComparable>> objectList= new List<BaseClass<IComparable>>();
  ChildClass<int> childObject= new ChildClass<int>();
  ChildClass<double> childObject2= new ChildClass<double>()
  //both int and double are IComparable

//the bellow code dosent compile, it syas it cannot be casted, i dont understand why becuse they are his child class:

Show source
| generics   | c#   | inheritance   | oop   2017-01-05 13:01 1 Answers

Answers to c# generic inheritance base class to child class ( 1 )

  1. 2017-01-05 15:01

    I am not sure what you need that list for, but as juharr said in your comments this is an issue with covariance. If you absolutely need to find a generic way to get the child classes based on some sort of value in a list, or some set of values, you can still do it. Although, it is a bit round-a-bout and maybe not the best solution...

    Something like so:

    private void Main()
        var values = new List<IComparable>();
        foreach (var value in values) {
            Console.WriteLine(value); // The value
            var childClass = BuildChild(value);
            Console.WriteLine(childClass.GetType().FullName); // The type
            // Using dynamic will work
    private static object BuildChild(IComparable value)
        if (value == null)
            throw new ArgumentNullException(nameof(value));
        Type valueType = value.GetType();
        Type childClassType = typeof(ChildClass<>).MakeGenericType(valueType);
        return Activator.CreateInstance(childClassType);
    // Define other methods and classes here
    public abstract class BaseClass<T> where T : IComparable
    public class ChildClass<T> : BaseClass<T> where T : IComparable
        public void DoWork(T value) {

    Note that because you are using reflection to resolve the types this method is a tad slower than when you have the pre-instantiated instances. I am not sure how experienced you are with reflection and dynamic invocation, so this is just a reminder!

    Like I said, I have no idea what you need this for... or why you are needing the specific subclasses in a list. This solution is sort of another way you could get a similar functionality by just generating the the required class at runtime and on the fly.

    Another option would involve removing the generic constraint on the base class and using reflection to resolve the child or to just remove the generic constraint all together and potentially resolve the type via method-level generics. However, not knowing what you need keeps me from helping you find the optimal solution, so these are just ideas.

Leave a reply to - c# generic inheritance base class to child class

◀ Go back