Search code examples
c#genericsinheritancecovariance

Conversion not possible in dotnet core with inheritance and generics


Here is my current code (.net core):

Box code:

class Box { }

SpeicalBox code:

class SpecialBox : Box { }

Stack code:

interface Stack<T> where T : Box 
{
    AnotherInterface<T> TheFunction();
}

SpecialStack code:

class SpecialStack : Stack<SpecialBox> { }

StacksHolder code:

class StacksHolder
{
    private List<Stack<Box>> Stacks = new List<Stack<Box>>();
}

This is the error i get:

I am getting the following error if I am trying to add a SpecialStack to the list of Stacks in the StacksHolder:

cannot convert from 'SpecialStack' to 'Stack'

The code I use for that:

class StacksHolder
{
    private List<Stack<Box>> Stacks = new List<Stack<Box>>();

    public StacksHolder()
    {
        Stacks.Add(new SpecialStack());
    }
}

Does anyone have an idea why that does not work? I would be very happy if anyone could explain me, how to fix it.

Thanks in advance!


Solution

  • I could fix my problem by adding the out keyword to both interfaces Stack and AnotherStack.

    Thank you @Lee for bringing me to the solution!

    Solution Code:

    Stack code:

    interface Stack<out T> where T : Box 
    {
        AnotherInterface<T> TheFunction();
    }
    

    AnotherInterface code:

    interface AnotherInterface<out T> where T : Box
    {
    }