Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Anonymous Type and Dynamics... Confused

I found something inside .NET that works a bit differently that I would have expected. The code I am pasting won't make sense, but it is a condensed version of a much more complicated function I have. I'm essentially getting the anonymous type information as a parameter (no instance created yet of the anonymous type) and I need to create a list of that 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.

Thanks!

like image 612
Terry Avatar asked Dec 29 '25 01:12

Terry


1 Answers

Because in your method B, you are using the explicit IList.Add(object) which takes an object and tries to cast it to your anonymous type. In method A you have a List<anonymous type> and you're using the generic Add method and trying to Add an object, but you get the RuntimeBinderException because it is expecting the correctly casted type. If you weren't using a dynamic you'd see the compiler error. To use the explicit IList.Add, change your method A with

((IList)list).Add(
    Activator.CreateInstance(newItem.GetType(), 
        new object[] { Guid.NewGuid(), "Test 2" }));
like image 199
Yuriy Faktorovich Avatar answered Dec 31 '25 00:12

Yuriy Faktorovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!