Ruskin
Ruskin

Reputation: 1504

Contra/covariance issues with generics

I am try to create types of particular classes but I can't return them back out as their generic representation, can someone please tell me how to achieve that? I am a bit light on contra/covariance magic

public DashboardNotification<IDashboardEntry> Get()
{
    //return new MyNotWorkingNotification(); // doesn't compile, I want to achieve this
    return new MyWorkingNotification(); // compiles
}

public class DashboardNotification<T> where T : IDashboardEntry
{
}

public interface IDashboardEntry
{
}

public class MyNotWorkingNotification : DashboardNotification<MyDashboardEntry>
{
}

public class MyWorkingNotification : DashboardNotification<IDashboardEntry>
{
}

public class MyDashboardEntry : IDashboardEntry
{
}

Upvotes: 3

Views: 209

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660503

Let's rename your types.

interface IAnimal {}
class Cage<T> where T : IAnimal {}
class Tiger : IAnimal {}

Your question is: I have a Cage<Tiger> and I want it to be used as a Cage<IAnimal> because a tiger is an animal.

Now do you see why that is illegal? A cage of tigers can only hold tigers; a cage of animals can hold any animal. If a cage of tigers could be used as a cage of animals then you could put a fish into the tiger cage, which would make neither the tiger nor the fish very happy.

What you want is generic class covariance, but C# only supports generic covariance on interfaces and delegates.

Upvotes: 6

Related Questions