Works
private void Add<H>(H toAdd, IList<dynamic> list)
{
list.Add(toAdd);
}
Doesn’t work
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd);
}
As you can imagine, the error is
The best overloaded method match for 'System.Collections.Generic.ICollection<System.Collections.Generic.IList<dynamic>>.Add(System.Collections.Generic.IList<dynamic>)' has some invalid arguments
If anyone knows why this is happening or even better, how to fix it, I am very curious. I assume it has to do with Generic Variance but the dynamic makes me less sure.
Thanks, Tom
Edit
//doesn't work
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list) where H : object
{
list.Add(toAdd);
}
//works
//this isn't good enough however because I only want to be able to
//have one type of object in toAdd
private void Add(IList<object> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd);
}
//works
private void Add<H>(IList<H> toAdd, IList<IList<dynamic>> list)
{
list.Add(toAdd.Cast<dynamic>().ToList());
}
private void Foo()
{
//works
IList<dynamic> list1 = new List<object>();
//works
IList<object> list2 = new List<dynamic>();
//works
IList<IList<dynamic>> list4 = new List<IList<object>>();
//works
IList<IList<object>> list3 = new List<IList<dynamic>>();
}
I added a couple more examples (not all surprising) just to illustrate
That’s because you cannot cast an
IList<H>to anIList<dynamic>. Imagine what happens:You can try to keep a list of
IEnumerable<dynamic>instead ofIList<dynamic>, sinceIEnumerable<out T>has a covariant type parameter.