Overload the += event operator
-
16-09-2019 - |
Question
Is there a way to overload the event += and -= operators in C#? What I want to do is take an event listener and register it to different events. So something like this:
SomeEvent += new Event(EventMethod);
Then instead of attaching to SomeEvent, it actually attaches to different events:
DifferentEvent += (the listener above);
AnotherDiffEvent += (the listener above);
Thanks
Solution
It's not really overloading, but here is how you do it:
public event MyDelegate SomeEvent
{
add
{
DifferentEvent += value;
AnotherDiffEvent += value;
}
remove
{
DifferentEvent -= value;
AnotherDiffEvent-= value;
}
}
More information on this on switchonthecode.com
OTHER TIPS
You can do this In C# using custom event accessors.
public EventHandler DiffEvent;
public EventHandler AnotherDiffEvent;
public event EventHandler SomeEvent
{
add
{
DiffEvent += value;
AnotherDiffEvent += value;
}
remove
{
DiffEvent -= value;
AnotherDiffEvent -= value;
}
}
Which means you can simply call SomeEvent += new EventHandler(Foo)
or SomeEvent -= new EventHandler(Foo)
and the appropiate event handlers will be added/removed automatically.
You can combine delegates using + and - operators
See How to: Combine Delegates (Multicast Delegates)(C# Programming Guide)
If you are just looking to get away from some typing, you can do this
SomeEvent += MyMethod;