Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast generic type to interface type constraint

Tags:

c#

.net

Is is possible to make the following compile without:

  1. Making IFooCollection generic
  2. Explicitly implementing IFooCollection.Items on FooCollection and performing an explicit cast.

public interface IFoo
{

}

public interface IFooCollection
{
    IEnumerable<IFoo> Items { get; }
}

public class FooCollection<T> : IFooCollection where T : IFoo
{
    public IEnumerable<T> Items { get; set; }
}

I'm happy enough with the second solution (implementing the interface explicitly) but would like to understand why I need to cast T as IFoo when we have a generic constraint specifying that T must implement IFoo.

like image 729
Ben Foster Avatar asked Aug 31 '12 11:08

Ben Foster


1 Answers

The reason is the following:

IFooCollection.Items can contain any class that implements IFoo. So it can contain FooA, FooB, FooC at the same time.

FooCollection<FooA>.Items on the other hand can only contain elements of type FooA. Trying to cast FooB or FooC to FooA would yield an InvalidCastException although all implement IFoo.

like image 192
Daniel Hilgarth Avatar answered Oct 15 '22 08:10

Daniel Hilgarth