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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With