Question

// 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?)

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top