From this MSDN article, there’s quite a few ways to hook up a delegate using reflection.
It seems the best way is with the CreateDelegate method:
Delegate d = Delegate.CreateDelegate(delegateType, targetObject, handlerMethodName);
Under normal circumstances, I’d be pointing to the handler method that is within the targetObject class.
But what if the delegate was created anonymously? Example:
public delegate void SelectedVehiclesCollectionDelegate(string query, List<Vehicles> list);
...
myObject.SelectedVehiclesCollection = (query, list) =>
{
//assign list of vehicles to list matching query
};
There’s not a method within the class definition to which the delegate is referencing. I need to invoke this delegate which is unknown at runtime, obtaining the list of items are a result.
Ok, looks like my terminology got the best of me. Wasnt aiming at creating a handler but invoke what’s already there (Tomas Petricek’s answer still gives me some good insight though).
Given your comment, it sounds like this is about calling a delegate rather than creating one, in which case
Delegate.DynamicInvokeis probably what you’re after, if you really don’t know the relevant delegate type at compile time.If you do know the relevant delegate type, just not the property name, you can cast: