Henk
Henk

Reputation: 704

Combining List<Base> with List<Derived>

How can I do the follwing:

public class BaseItem
{
    public string Title { get; set; }
}

public class DerivedItem : BaseItem
{
    public string Description { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<BaseItem> baseList = new List<BaseItem>();
        List<DerivedItem> derivedList = new List<DerivedItem>();
        baseList.Add(new BaseItem() { Title = "tester"});
        derivedList.Add(new DerivedItem() { Title = "derivedTester", Description = "The Description" });

        baseList.AddRange(derivedList);
    }
}

Thanks, Henk

Upvotes: 4

Views: 1215

Answers (2)

lasseeskildsen
lasseeskildsen

Reputation: 609

Assuming you're using .net 3.5, try adding the items of the derivedList like this:

baseList.AddRange(derivedList.Cast<BaseItem>());

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

In C# 3.0/.NET 3.5, IEnumerable<T> is not covariant. However, this would probably work OK in C# 4.0/.NET 4.0.

For now, you could (in .NET 3.5) use:

baseList.AddRange(derivedList.Cast<BaseItem>());

(note that you'll need "using System.Linq;" at the top of the file)

Before that... probably easiest just to loop:

foreach(BaseItem item in derivedList) {baseList.Add(item);}

Upvotes: 12

Related Questions