Tuesday, June 10, 2014

creating objects dynamically c#

Hi,

today I am writing on my term paper and I needed a way to create objects dynamically while having a type object.

I tried the old-school way as following:

1
2
var x = typeof(List<string>).GetConstructor(
   new Type[] { }).Invoke(new object[] { });

and got my expected result. This was kind a hard way but it worked as it did 10 years ago.

My problem was now: I knew that the object to create is List, but wanted to have string dynamically passed in by a parameter or generic into my function. I found the following solution after about an hour of googling:


1
2
var y = Activator.CreateInstance(
                typeof(List<>).MakeGenericType(typeof(string)));

MakeGenericType does the trick. Using activator is not necessary, but seems to be much easier to use and perfect for my use case. With shame I have to admit that Activator seems to exists since .NET framework 1.1 (= 2003). Anyway, I love it.

Kind regards,
Daniel

No comments: