Reputation: 1
I was writing some C# code which uses events, and Resharper asked if I want to create an event invocator. It generated the following code:
LowFuel handler = lowFuel;
if (handler != null) handler();
Maybe I am missing something or a little rusty, but what is an event invocator? I know about the handler which is where the actual logic for the event will go.
Thanks
Upvotes: 0
Views: 581
Reputation: 292555
As the name implies, it's a method used to raise the event. It's usually better than directly invoking the delegate, for several reasons, because it checks whether the handler is null before trying to invoke it (so you don't need to check that every time you want to invoke the event).
Also, note that by default Resharper creates the event invocator as public and non virtual. IMHO it shouldn't be public, it usually doesn't make sense to invoke an event from outside the class that declares it. Also, it's often useful to make this method virtual, so you can override it in derived classes, rather than subscribe to the event of the base class. I always declare event invocators as follows:
protected virtual void OnFoo(FooEventArgs args)
{
var handler = Foo;
if (handler != null)
handler(this, args);
}
Upvotes: 3
Reputation: 137158
An event invocator (horrible term) is simply the code that invokes the event.
It's not 100% clear from your code example, but normally you'd declare LowFuel
separately from the usage (in an interface perhaps) which is why you need to check it exists before calling it.
Upvotes: 0