Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a list to a list with different but compatible generic type?

Tags:

c#

generics

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?

like image 860
justkevin Avatar asked Jan 27 '26 07:01

justkevin


1 Answers

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.

like image 129
Reed Copsey Avatar answered Jan 29 '26 20:01

Reed Copsey