List of anonymous type and dynamics ... Confused

I found something inside .NET that works slightly different than what I expected. The code I embed does not make sense, but it is a compressed version of the much more complex function that I have. I essentially get the information of an anonymous type as a parameter (an instance of an anonymous type not yet created), and I need to create a list of this type, populate it and then return the list. Now I found a solution, but I wanted to know why method B works, but not method A.

Method A:

static void Main(string[] args)
{
    var newItem = new {  ID = Guid.NewGuid(), Name = "Test" };
    dynamic list;

    list = Activator.CreateInstance(typeof(List<>).MakeGenericType(newItem.GetType()));

    list.Add(newItem);
    list.Add(Activator.CreateInstance(newItem.GetType(), new object[] { Guid.NewGuid(), "Test 2" }));
}

Method B:

static void Main(string[] args)
{
    var newItem = new {  ID = Guid.NewGuid(), Name = "Test" };
    System.Collections.IList list;

    list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(newItem.GetType()));

    list.Add(newItem);
    list.Add(Activator.CreateInstance(newItem.GetType(), new object[] { Guid.NewGuid(), "Test 2" }));
}

Again, I'm not looking for a solution, just curious why Method B works, but not Method A.

Thank!

+3
source share
2 answers

B IList.Add(object), . A List<anonymous type>, Add , RuntimeBinderException, . dynamic, . IList.Add, A

((IList)list).Add(
    Activator.CreateInstance(newItem.GetType(), 
        new object[] { Guid.NewGuid(), "Test 2" }));
+2

, , A, dynamic , . , # . , , , .

   static void Main(string[] args)
{
    var newItem = new {  ID = Guid.NewGuid(), Name = "Test" };
    dynamic list;

    list = Activator.CreateInstance(typeof(List<>).MakeGenericType(newItem.GetType()));

    list.Add(newItem);
    list.Add((dynamic)Activator.CreateInstance(newItem.GetType(), new object[] { Guid.NewGuid(), "Test 2" }));

}
0

Source: https://habr.com/ru/post/1790019/


All Articles