I wanted to do something like co-variance in C# but I dont have here any inheritance .
I have this code :
public interface IBirthday
{
void Dance ();
}
public class Birthday:IBirthday
{
public void Dance()
{}
}
void Main()
{
List<Birthday> l= new List<Birthday>();
List<IBirthday> d = l; //<--- How can I accomplish that ?
}
HOw can I make this work ? (besides iterating and build manually ( linq or loop))
List<IBirthday> d = list of birthdays ?
does iterating/linq is the only choice?
It’s not possible to assign a
List<Birthday>to aList<IBirthday>without creating a brand new list (it can be hidden from you, but it must happen somewhere).If what you were trying to do were possible then what would happen when someone did:
Well, it’s a
List<IBirthday>, so it thinks that it’s able to add the new item. But the underlying list is actually aList<Birthday>, and you can’t add anUnBirthdayto that list. Given the choice between allowing this and just crashing at runtime, C# made the decision (correctly, in my opinion) of just not allowing it in the first place.The only way to utilize generic argument covariance, which is what you’re trying to do, is to assign it to something that can only read information out, and never put information in. One example of this is
IEnumerable<T>. Every singleBirthdayis anIBirthday, and there’s no way forIEnumerableto be given anIBirthdaythat’s not aBirthday, so saying:works just fine.