Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance - How to create instances of classes that have parameterized constructors

Tags:

c#

.net

.net-3.5

I have read a few bits and bobs online about this topic but found none that work for me. What I am trying to do is create a class of a runtime Type.

I use Activator.CreateInstance which works fine for classes with constructors that contain no arguments. For those with arguments it throws an exception, is there a way around this?

I am more than happy to pass null values or empty values to the ctor so long as I can create the class itself.

like image 499
Chris Avatar asked Aug 17 '09 14:08

Chris


2 Answers

There is an overload that accepts arguments as a params object[]:

object obj = Activator.CreateInstance(typeof(StringBuilder), "abc"); 

Would this do? Alternative, you can use reflection to find the correct constructor:

Type[] argTypes = new Type[] {typeof(string)}; object[] argValues = new object[] {"abc"}; ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes); object obj = ctor.Invoke(argValues); 
like image 57
Marc Gravell Avatar answered Oct 02 '22 18:10

Marc Gravell


I eventually ended up doing something like this - some of the commentors hinted towards this solution anyway.

I basically iterated through all available constructors and chose the simplest. I then created null data to pass into the ctor (for what Im using it for this approach is fine)

Part of the code looks a little like this

// If we have a ctor that requires parameters then pass null values if (requiresParameters) {     List<object> parameters = new List<object>();     ParameterInfo[] pInfos = constructorInfos[0].GetParameters();      foreach (ParameterInfo pi in pInfos)     {         parameters.Add(createType(pi.ParameterType));     }      return constructorInfos[0].Invoke(parameters.ToArray()); } 
like image 45
Chris Avatar answered Oct 02 '22 18:10

Chris