Clear casting problem

// The Structure of the Container and the items public interface IContainer <TItem> where TItem : IItem { } public class AContainer : IContainer<ItemA> { } public interface IItem { } public class ItemA : IItem { } // Client app [Test] public void Test () { IContainer<IItem> container = new AContainer(); } 

Question: The following error occurs in the test. What could be a casting solution?

It is not possible to implicitly convert the type "AContainer" to "IContainer". Explicit conversion exists (are you skipping listing?)

0
source share
3 answers

Another covariant generation problem ...

Generic types in .NET are not covariant or contravariant - IContainer <ItemA> (which is an AC connector) is not a subclass of IContainer <IItem> - between these two valid actions there is no. This will be fixed in C # 4.

+3
source

If you want to use AContainer as an IContainer<IItem> , you also need to implement this interface:

 public class AContainer : IContainer<ItemA>, IContainer<IItem> 

You can implement it explicitly.

+1
source

All Articles