user1005016
user1005016

Reputation: 83

Create delegate dynamically from Type name

i would like to create a generic delegate but i only know the type while the execution.

here is the delegate that i want to create :

public delegate void MyDel<T>(T t,string msg);

and here is the method in which i want to instantiate and use the delegate

Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");    
Delegate test = Delegate.CreateDelegate(typeof(MyDel<typeSet>, method);

where typeSet is unknow for me at the compilation. and unfortunately, the method that i want to call is not static.

Does anyone have any idea ?

Thanks in advance

Upvotes: 2

Views: 827

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500375

You need to create the specific delegate type using MakeGenericType:

Type template = typeof(MyDel<>);
Type specific = template.MakeGenericType(typeSet);
Delegate test = Delegate.CreateDelegate(specific, method);

I think that's what you're after...

Upvotes: 4

Related Questions