PMOrion
PMOrion

Reputation: 169

Pass a dynamic type

I am aware of passing dynamic types with reflection but with the following class structure am having a little difficulty; where my calling class would be instantiating another class and calling a method on it's base class passing the method a dynamic type.

public class MainClass
{
    // var genericClass = new GenericClass();
    // genericClass.SomeMethod<T>();
    var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);
    Activator.CreateInstance(myDynamicType);
}

public class GenericClass : GenericBase
{
}

public abstract class GenericBase
{
   private readonly List<IMyInterface> myList = new List<IMyInterface>();

   public void SomeMethod<T>() where T : IMyInterface, new ()
   {
       myList.Add(new T());
   }
} 

Upvotes: 0

Views: 816

Answers (2)

flipchart
flipchart

Reputation: 6578

You have two options. The first involves modifying the SomeMethod<T> method to be non-generic or adding a non-generic overload:

public void SomeMethod(Type t) {
    var myInterface = (IMyInterface)Activator.CreateInstance(t);

    myList.Add(myInterface);
}

public void SomeMethod<T>() where T : IMyInterface, new ()
{
   SomeMethod(typeof(T));
}

Then call is as follows:

var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);  //I assume this is the type that you want to use as the generic constraint 'T' of SomeMethod<T>

var genericClass = new GenericClass();
genericClass.SomeMethod(myDynamicType);

Alternatively, you can leave the SomeMethod<T> method alone and invoke the method via reflection:

var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);  //I assume this is the type that you want to use as the generic constraint 'T' of SomeMethod<T>

var genericClass = new GenericClass();
var method = typeof(GenericClass).GetMethod("SomeMethod").MakeGenericMethod(myDynamicType);
method.Invoke(genericClass);

Upvotes: 0

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

You can change the method signature of SomeMethod<T>() with SomeMethod(Type t).

public void SomeMethod(Type t)
    {
        if (t.GetInterfaces().Contains(typeof(IMyInterface)) && 
               t.GetConstructor(Type.EmptyTypes)!=null)
        {
            var obj=(IMyInterface)Activator.CreateInstance(t);
            myList.Add(obj);
        }
    }

Upvotes: 1

Related Questions