user518333
user518333

Reputation: 45

Delegates in C#

How to add a method to delegate Using reflection? Let us consider im having two assemblies,one AAA contains the definition of delegates and another one BBB contains the method to be added to the delegate.In BBB i have add the method to the delegate in AAA.How to accomplish this scenario?

Upvotes: 0

Views: 206

Answers (1)

thecoop
thecoop

Reputation: 46158

Something like this (warning - not compile tested):

// get the methodinfo for the method you want to add
MethodInfo methodToAdd = typeof(AAA).GetMethod("MyMethod");

// create a delegate instance for it
Delegate methodDelegate = Delegate.CreateDelegate(typeof(BBB.MyDelegate), methodToAdd);

// get the event you want to add to
EventInfo eventToAddMethodTo = typeof(BBB).GetEvent("MyEvent");

// call the event's add method, with the delegate you want to add
eventToAddMethodTo.AddEventHandler(null /*or the AAA instance if this is a non-static event */, methodDelegate);

If it's not an event you want to add to, but just another Delegate, then you use Delegate.Combine:

Delegate combinedDelegate = Delegate.Combine(oldDelegate, methodDelegate);

Upvotes: 3

Related Questions