Search code examples
c#wpfdynamiccovariancegeneric-collections

Covariance in generic collections


I would like to do this

List<anotherclass> ls = new List<anotherclass> {new anotherclass{Name = "me"}};    
myGrid.ItemSource = ls;

at some other place

var d = myGrid.ItemSource as IEnumerable<Object>;    
var e = d as ICollection<dynamic>;
e.Add(new anotherclass());

I need to access the itemsource at different areas of the program. I need to add items to the List without compile time type information. Casting to IEnumerable works, but because I need to add items to the collection I need more than that, hence trying to cast it to a collection.

How can it be possible?


Solution

  • List<T> implements IList. So as long as you're sure you're adding the right type of object, you can use the Add method of this interface:

    var d = (IList)myGrid.ItemSource;        
    d.Add(new anotherclass());