Combining the <Base> List with the <Derivatives> List

How can I do the following:

 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

+4
source share
2 answers

In C # 3.0 / .NET 3.5, IEnumerable<T> not covariant. However, this is likely to work fine in C # 4.0 / .NET 4.0.

Now you can (in .NET 3.5) use:

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

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

Before that ... perhaps the easiest way is to just loop:

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

Assuming you are using .net 3.5, try adding items to the derived list as follows:

 baseList.AddRange(derivedList.Cast<BaseItem>()); 
+1
source

All Articles