Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting generic classes in C#

I have a problem with casting generic types.

For example I have classes:

public class Dog
{
}

public class Husky : Dog
{

}

public class MyWrapper<T> where T : class
{
}

and then I want to do something like this, but I don't know how

MyWrapper<Husky> husky = new MyWrapper<Husky>();
List<MyWrapper<Dog>> dogs= new List<MyWrapper<Dog>>();
dogs.Add(husky); // how to cast husky to MyWrapper<Dog>?

EDIT: Changed Animal<T> to MyWrapper<T>, so it will be more adequate example

like image 368
vanilla161 Avatar asked Jan 23 '13 08:01

vanilla161


1 Answers

You could use the generic covariance of interfaces in C# 4 or later. In order to do so, you'd need to define a covariant interface (using out) and have MyWrapper implement that interface:

public class Dog 
{
}

public class Husky : Dog
{
}

public class MyWrapper<T> : IMyWrapper<T> where T : class
{
}

public interface IMyWrapper<out T> where T : class
{
}

Then you can do this:

var husky = new MyWrapper<Husky>();
var dogs = new List<IMyWrapper<Dog>>();
dogs.Add(husky);
like image 145
Eren Ersönmez Avatar answered Sep 30 '22 00:09

Eren Ersönmez