Say that I have a class, Foo, looking something like this:
public class Foo : IFoo
{
public Foo()
{
Bars = new List<dynamic>();
}
public IList<dynamic> Bars { get; set; }
}
The interface IFoo looks like:
public interface IFoo
{
IList<dynamic> Bars { get; set; }
}
Now, when I do the following:
IFoo foo = new Foo();
dynamic a = new System.Dynamic.ExpandoObject();
a.Prop = 10000;
dynamic b = new System.Dynamic.ExpandoObject();
b.Prop = "Some Text";
foo.Bars.Add(a); // Throws an 'System.Collections.Generic.IList<object>' does not contain a definition for 'Add' - exception!!!!!
foo.Bars.Add(b); // Same here!!!!!
What am I doing wrong here?????
This is a known dynamic binding issue.
Here are some work arounds.
Use
ICollection<dynamic>
instead:Or straight up
List<dynamic>
:Or use
dynamic foo
:Or don't dynamic bind
add
, by casting toobject
:Or be more expressive using a third party framework like my impromptu interface with ActLike & Prototype Builder Syntax (in nuget).
I'm not sure if this subverts your particular use case, but:
Try explicitly casting
Bars
toSystem.Collections.IList
.Source: https://stackoverflow.com/a/9468123/364
Alternatively, just redefine
Bars
asIList
rather thanIList<dynamic>
in your interface + class.