justkevin
justkevin

Reputation: 3199

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

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?

Upvotes: 3

Views: 75

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564403

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.

Upvotes: 5

Servy
Servy

Reputation: 203821

You're using a version of C# before C# 4.0 when covariance was added. If you switch to C# 4.0+ then you are able to leverage covariance, in particular here, IEnumerable<T> will become covariant, allowing you to treat an IEnumerable<ShipModule> as if it were an IEnumerable<IRepairable>.

Upvotes: 0

Related Questions