///
/// Creates an instance of the generic type specified using the parameters
/// specified.
///
/// The type to instantiate.
/// The System.Type being instantiated.
/// The array of parameters to use when calling the constructor.
/// An instance of the specified type.
///
///
/// If there is not a constructor that matches the parameters then an is
/// thrown.
///
///
/// typeof(MyObject).CreateInstance(new object[] { 1, 3.0M, "Final Parameter" });
///
public static T CreateInstance<T>(this Type type, object[] parameters)
{
parameters.ExceptionIfNullOrEmpty("The parameters array must not be null.", "parameters");
var ctor = type.GetConstructor(parameters.Select(parameter => parameter.IsNull() ? typeof (object) : parameter.GetType()).ToArray());
if (ctor.IsNull())
{
throw new ArgumentException("There are no constructors for " +
type.FullName + " that match the types provided.");
}
var result = (T) ctor.Invoke(parameters);
return result;
}
|