I'm using the following method to instantiate an object via reflection
Activator.CreateInstance(Type type, params object[] parameters)
Where "parameters" is the list of parameters passed to the constructor at runtime.
However, I'd like this process to be more intuitive to other developers on the team and rather than passing object[] array of parameters, I would like them to pass an anonymous object, e.g.
// note, invalid code
Activator.CreateInstance(typeof(MyType), new { paramName1 = "abc", paramName2 = "xyz})
Since the framework method doesn't support it, does anyone have an example of the code that translates an anonymous object into an array? Note that the order of the parameters is important to the Activator.CreateInstance() method since that's how it does parameter matching. Obviously this is error prone, that's why I'd prefer to use an anonymous type.
Any suggestions are gladly appreciated.
Alec.
I wouldn't use Activator.CreateInstance
for this. I'd use Type.GetConstructors()
to get all the constructors, and then find one which has the same number of parameters as the anonymous type has properties, and with the same names. If there might be multiple such constructors with different types, you'll need to add extra logic to check that each parameter type is compatible with the relevant property type.
Something like:
public object CreateInstance(Type type, Object parameterMapping)
{
var ctors = type.GetConstructors();
var properties = parameterMapping.GetType().GetProperties();
foreach (var ctor in ctors)
{
var parameters = ctor.GetParameters();
if (parameters.Length != properties.Length)
{
continue;
}
object[] args = new object[parameters.Length];
bool success = true;
for (int i = 0; i < parameters.Length;
{
var property = parameterMapping.GetType().GetProperty(parameter.Name);
if (property == null)
{
success = false;
break;
}
// TODO: Check property type is appropriate too
args[i] = property.GetValue(parameterMapping, null);
}
if (!success)
{
continue;
}
return ctor.Invoke(args);
}
throw new ArgumentException("No suitable constructor found");
}
See more on this question at Stackoverflow