How to Pass Parameters to Activator.CreateInstance<T>()

C#GenericsCreateinstance

C# Problem Overview


I want to create an instance of a type that I specify in a generic method that I have. This type has a number of overloaded constructors. I'd like to be able to pass arguments to the constructors, but

Activator.CreateInstance<T>()

doesn't see to have this as an option.

Is there another way to do it?

C# Solutions


Solution 1 - C#

Yes.

(T)Activator.CreateInstance(typeof(T), param1, param2);

Solution 2 - C#

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);
}

Solution 3 - C#

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.

Performance comparison

Solution 4 - C#

As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:

https://stackoverflow.com/questions/2024435/how-to-pass-ctor-args-in-activator-createinstance

Solution 5 - C#

public class AssemblyLoader<T>  where T:class
{
    public void(){
        var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll") 
    }

    public T Load(string assemblyFile, string objectToInstantiate) 
    {
        var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();

        return loaded as T;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveDevView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#sudhAnsu63View Answer on Stackoverflow
Solution 3 - C#Anestis KivranoglouView Answer on Stackoverflow
Solution 4 - C#thamesView Answer on Stackoverflow
Solution 5 - C#Carga dinamica de dllView Answer on Stackoverflow