How to Dynamically Create Generic C# Object Using Reflection

How to dynamically create generic C# object using reflection?

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

To see where I came up with backtick1 for the name of the generic class, see this article.

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

Create instance of generic class with dynamic generic type parameter

I found very simple solution to problem. There is no need to cast object to specific type T, just use dynamic keyword instead of casting

   Type myGeneric = typeof(MyComparer<>);
Type constructedClass = myGeneric.MakeGenericType(T);
object created = Activator.CreateInstance(constructedClass);
dynamic comparer = created; // No need to cast created object to T

and then I can use comparer normally to call its methods like:

   return comparer.Equals(myResultAsT, correctResultAsT);

According to LueTm comments, it is probably possible to use reflection again and call comparer methods, but this solution looks much easier.

Creating an object of Generic Class with dynamically generated type

Thanks All for the Help I was able to do it by this way

        var someType = Type.GetType("MyProject.Employee");
var genericType = typeof(Convert<>).MakeGenericType(new[] { someType });
var instance = Activator.CreateInstance(genericType);

string instanceType = instance.GetType().FullName;

MethodInfo methodInfo = Type.GetType(instanceType).GetMethod("Translate");
genericType.InvokeMember(methodInfo.Name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, instance, new object[] { lstEmp, "Name", "City" });

ishan

instantiate a generic class using reflection

Regarding your update, you can pass any Type to MakeGenericType. For example, the following also works:

var myObject = new MyClass();

var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(typeof(MyClass)), myObject);

Console.WriteLine(myGenericObject.GetType());

Outputs:

ConsoleApplication1.GenericClass`1[ConsoleApplication1.MyClass]

myObject.GetType() also does the same thing:

var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(myObject.GetType()), myObject);

C# Generics specify type dynamically via reflection

You can use reflection to do this by utilizing Invoke and MakeGenericMethod.

You will need to know the name of the class it is executing in, lets call it ClassName. The binding flags are also very important, if they are incorrect (guessing here since you don't show a method signature) then the MethodInfo will be null and you will get an exception.

if(/*noted conditions in question*/)
{
Type itemType = propertyType.GetGenericArguments()[0];
Type ThisClass = typeof(ClassName);
MethodInfo mi = ThisClass.GetMethod("MyGenericMethod", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo miConstructed = mi.MakeGenericMethod(itemType);
object[] args = { url };
var result = miConstructed.Invoke(this, args);
}

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.

As noted, a lot of this is simpler as of C# 4 using dynamic - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.

How to call a Generic method on a dynamic type in C#

Since your type is dynamic, you won't know the type of the generic parameter until run-time. For this reason, you must also treat the function as dynamic, because you won't know the "type" of the function's generic signature until run-time.

You must use reflection to call a generic function dynamically. See How do I use reflection to call a generic method?



Related Topics



Leave a reply



Submit