Coder Perfect

Parameters to Activator and How to Pass Them CreateInstance()


I’d like to make an instance of a type that I specify in a generic method. There are several overloaded constructors in this type. I’d like to be able to pass constructor arguments, however


This does not appear to be an option.

Is there a different way?

Asked by DaveDev

Solution #1


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

Answered by SLaks

Solution #2

Another option for passing inputs to CreateInstance is to use named parameters.

You can use this information to pass an array to CreateInstance. You can have 0 or many arguments using this method.

public T CreateInstance<T>(params object[] paramArray)
  return (T)Activator.CreateInstance(typeof(T), args:paramArray);

Answered by sudhAnsu63

Solution #3

Keep in mind that supplying arguments to Activator is not permitted. When compared to parameterless creation, CreateInstance has a large speed difference.

There are better alternatives for dynamically creating objects using pre compiled lambda. Of course, performance is always subjective, and whether it is worthwhile or not depends on the circumstances.

This article contains information regarding the topic.

Graph is taken from the article and represents time taken in ms per 1000 calls.

Answered by Anestis Kivranoglou

Solution #4

As a substitute for Activator. In the linked url, CreateInstance, FastObjectFactory outperforms Activator (as of.NET 4.0) and greatly outperforms.NET 3.5. With.NET 4.5, no tests or statistics were performed. For stats, information, and code, see this StackOverflow post:

In Activator, how to pass ctor args. Is it better to use CreateInstance or IL?

Answered by thames

Solution #5

public class AssemblyLoader<T>  where T:class
    public void(){
        var res = Load(@"C:\test\", "") 

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

        return loaded as T;

Answered by Carga dinamica de dll

Post is based on