I'm trying to copy elements from a list of a generic type (ShipModule) to another list of a different, but compatible type (IRepairable).
List<ShipModule> modules = new List<ShipModule>();
// Add some modules...
List<IRepairable> repairables;
repairables = new List<IRepairable>();
// This is an error:
repairables.AddRange(modules);
// So is this:
repairables = new List<IRepairable>(modules);
// This is okay:
foreach(ShipModule module in modules) {
repairables.Add(module);
}
ShipModule implements IRepairable, so all the elements can be safely added, but I can't use the copy constructor or AddRange. Why?
If yo'ure using .NET 3.5, you can use Enumerable.Cast:
repairables = new List<IRepairable>(modules.Cast<IRepairable>());
Note that your versions do work in C#4/.NET 4 and later, as IEnumerable<T> became IEnumerable<out T>, and C# 4 supports covariance in generics.
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