I like to understand how dynamic keyword works in this following code. I found a number of posts that talks about how calling Add() on IList cause RuntimeBinderException, but doesn't quite explain why the following code does not work:
[TestFixture]
public class TestDynamicOfIList
{
[Test]
public void Test1()
{
dynamic d1 = new ClassA();
dynamic d2 = new ClassA();
List<dynamic> dynamicList = new List<dynamic>();
dynamicList.Add(d1);
dynamicList.Add(d2);
ClassGroup group = new ClassGroup();
foreach (dynamic dynamicClassA in dynamicList)
{
// using var will fail during runtime! Need to use explicit type
var sameObject = DoNothing(dynamicClassA);
group.ClassAList.Add(sameObject);
}
}
private ClassA DoNothing(dynamic classA)
{
return classA;
}
public class ClassA
{
}
public class ClassGroup
{
public IList<ClassA> ClassAList { get; } = new List<ClassA>();
}
}
}
In the above code, the ClassGroup.ClassAList property has a defined class 'ClassA' for the generic IList<>, I can't see why the compiler failed to do type checking, nor the it fails during runtime.
Here a couple of similar questions that I found on StackOverflow:
How to create a List with a dynamic object type C#
Does not contain a definition for "Add"
Why when I use var sameObject
it will not work it, but using ClassA sameObject
it works fine? It seems to think that the type of sameObject
variable is dynamic, when the method DoNothing()
clearly returns ClassA