0

The requirement is that object A subscribes to B's event which carries int as an argument. I've done this in given manner:

public delegate void BackToBase(int i);
public event BackToBase BackToBaseEvent;

...
if (this.BackToBaseEvent != null)
    this.BackToBaseEvent(5);

But it seems to me there is a shorter way to do that. Is there?

ren
  • 3,843
  • 9
  • 50
  • 95
  • Well, for starters, you can use `Action` instead of defining your own delegate. – Servy Sep 25 '12 at 16:59
  • 5
    Your title talks about *subscribing* to an event, but your question looks like it's really about *raising* an event. – Jon Skeet Sep 25 '12 at 17:00
  • I agree with Jon. You should do BackToBaseEvent += ... to subscribe to it. – Alex Mendez Sep 25 '12 at 17:01
  • 2
    Also, the way you're checking for a null handler is prone to errors in multithreaded code. Instead, do something like http://stackoverflow.com/a/282741/232566 – RQDQ Sep 25 '12 at 17:17
  • You could initialise your event with a no-op handler, or you could create an extension method. See [Raising C# events with an extension method - is it bad?](http://stackoverflow.com/questions/231525/raising-c-sharp-events-with-an-extension-method-is-it-bad) – Justin Sep 25 '12 at 17:24

2 Answers2

2

You could marginally shorten this by using a generic delegate like EventHandler<T>:

public event EventHandler<int> BackToBaseEvent;

The null check is pretty important though.

Rex M
  • 142,167
  • 33
  • 283
  • 313
2

You can initialize the event handler to an empty delegate in the ctor, and then you don't need to check because the delegate will never be null. E.g.

this.BackToBaseEvent += (s, e) => {};

And then you just do.

this.BackToBaseEvent(this, new MyEventArgs(5));

Be sure to observe the event handling patterns, using the right delegates and event arg classes.

If you do want to check for null (to avoid the overhead of invoking an empty action) use a local variable as described in http://msdn.microsoft.com/en-us/library/edzehd2t.aspx to avoid threading issues.

fsimonazzi
  • 2,975
  • 15
  • 13