NWoodsman
NWoodsman

Reputation: 505

Subscribe multiple methods in one line of code

Given:

btn1.MouseDown += someMethod1;
btn1.MouseDown += someMethod2;
btn1.MouseDown += someMethod3;

How can I define a proper structure to allow this:

btn1.MouseDown += someMethods;

Upvotes: 1

Views: 803

Answers (4)

Sandeep
Sandeep

Reputation: 399

You can use delegate.combine or just use '+' operator to chain multiple delegates.

btn1.MouseDown = new EventHandler(Method1) + new EventHandler(Method2) + new EventHandler(Method3) + ...;

Both are essentially the same.

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117174

This might just be a trivial way of doing it, but you can do this:

EventHandler someMethods = someMethod1;

someMethods += someMethod2;
someMethods += someMethod3;

btn1.MouseDown += someMethods;

Upvotes: 1

Jakub Lortz
Jakub Lortz

Reputation: 14894

You can use Delegate.Combine to create a single delegate. Something like this (with different delegate types probably):

EventHandler handler = (EventHandler)Delegate.Combine((EventHandler)someMethod1,
                                                      (EventHandler)someMethod2,
                                                      (EventHandler)someMethod3);
SomeEvent += handler;

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156708

Typically the thing to do would be to have a collection of methods, and iterate over them:

foreach (var f in new EventHandler[]{someMethod1, someMethod2, someMethod3})
{
    btn1.MouseDown += f;
}

This could be turned into a single line using List.ForAll() if you want to use that instead of a foreach.

Upvotes: 0

Related Questions