0
// 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 : In test the following error occures. What can be the solution for casting?

Cannot implicitly convert type 'AContainer' to 'IContainer'. An explicit conversion exists (are you missing a cast?)

jack-london
  • 1,599
  • 3
  • 21
  • 42

3 Answers3

3

Another generics covariant problem...

Generic types in .NET are not covariant or contravariant - IContainer<ItemA> (which is what AContainer is) is not a subclass of IContainer<IItem> - there is no valid cast between the two. This will be fixed in C# 4.

thecoop
  • 45,220
  • 19
  • 132
  • 189
  • 3
    I note that in C# 4 we are adding covariance and contravariance **but** only on interfaces and delegates with reference type arguments in the varying positions, and only those interfaces and delegates which are known at compile time to be safe for variance. – Eric Lippert Sep 18 '09 at 14:59
1

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

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

You may implement it explicitly.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
0

You can also consider Simulated Covariance for .NET Generics by Krzysztof Cwalina

Dzmitry Huba
  • 4,493
  • 20
  • 19