Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contra/covariance issues with generics

Tags:

c#

.net

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
{
}
like image 213
Ruskin Avatar asked Nov 19 '25 05:11

Ruskin


1 Answers

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.

like image 96
Eric Lippert Avatar answered Nov 21 '25 19:11

Eric Lippert