How to Pass Parameters to Activator.CreateInstance<T>()
Yes.
(T)Activator.CreateInstance(typeof(T), param1, param2);
There is another way to pass arguments to CreateInstance through named parameters.
Based on that, you can pass a array towards CreateInstance
. This will allow you to have 0 or multiple arguments.
public T CreateInstance<T>(params object[] paramArray)
{
return (T)Activator.CreateInstance(typeof(T), args:paramArray);
}
Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.
There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.
Details about the issue on this article.
Graph is taken from the article and represents time taken in ms per 1000 calls.