Search code examples
c#genericsinheritancecasting

How do you cast an generic class into an generic class of object?


let's say that you have 2 classes:

public abstract class Foo<T> {
    public abstract T DoSomething();
}

public class FooInt : Foo<int> {
    public override int DoSomething() {
        return 42;
    }
}

I want to cast FooInt into Foo<object>. And it is hard to restructure the code because I have a List<Foo<object>> that stores all the Foo class instances. And I do want to keep the overrides of FooInt.


I have tried this:

public static implicit operator Foo<object>(Foo<T> field) { return (Foo<object>)field; }

But I got an Overflow Exception, because it called itself. Then I tried this:

public static implicit operator Foo<object>(Foo<T> field) { return (field as Foo<object>)!; }

But that returned null. And I tried this:

public static implicit operator Foo<object>(Foo<T> field) { return (Foo<object>)(object)field;}

But that gave an Invalid Cast Exception. And I also tried removing the cast but that didn't work either.


Solution

  • @Fildor comments , like this

    public interface IFoo
    {
        void DoSome();
    }
    
    public abstract class Foo<T> : IFoo
    {
        public abstract T DoSomething();
        public void DoSome()
        {
            DoSomething();
        }
    }
    
    public class FooInt : Foo<int>
    {
        public override int DoSomething()
        {
            return 42;
        }
    }
    public class FooDouble : Foo<double>
    {
        public override double DoSomething()
        {
            return 42.0;
        }
    }
    
    
    List<IFoo> list = new List<IFoo>()
       {
           new FooInt(),
           new FooDouble()
       };
     foreach (var item in list)
     {
         item.DoSome();
     }