views:

394

answers:

4

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

+9  A: 

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

Dykam
A: 

If you are just looking to get away from some typing, you can do this

SomeEvent += MyMethod;
Chris Brandsma
+3  A: 

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.

Noldorin
A: 

You can combine delegates using + and - operators

See How to: Combine Delegates (Multicast Delegates)(C# Programming Guide)

Bogdan_Ch