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!
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" }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With