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
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);
}
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.
Related
I'm studying some examples provided by Microsoft for win8 development. I opened BasicControls sample and noticed LayoutAwarePage class and more precisely ObservableDictionary class. Reading about implementing events and raising them I can't see who's responsible to raise MapChangedEventHandler event. Based on parameters I believe that private void InvokeMapChanged(CollectionChange change, K key) method do this. But according to MSDN we need to provide a protected method that begins with On which doesn't occur in ObservableDictionary.
So, who raises MapChangedEventHandler?
An event in a class can be raised from within the class without need of an additional method to that.
So, if MapChangedEventHandler is an event, it can be called from inside the class just by this:
if (MapChangedEventHandler != null)
MapChangedEventHandler( parameters );
The only motive I can see (I'm not an expert) to the existance of those OnWhatever methods is to allow raising events from outside the class, or from some derived class, since events can only be raised from inside the declaring class.
Those OnWhatever methods must be some good practice (not a rule, nor a compiler rule).
Maybe they also take care of some additional stuff together with raising the event.
If they are not provided, probably they are not meant to be called from outside or from a derived class.
By the way, the MapChangedEventHandler is not an event. It's a delegate.
Events can be of that type, but their names are independant.
Like this:
class TestClass
{
these are the events of the class:
public event MapChangedEventHandler SomeEvent1;
public event MapChangedEventHandler SomeEvent2;
public event MapChangedEventHandler SomeEvent3;
//now this method calls the events (events can only be raised from inside the class)
public void SomeMethod()
{
//do lots of stuff
if (SomeEvent1 != null) SomeEvent1(whatever arguments it takes);
//do other stuff
if (SomeEvent2 != null) SomeEvent2(another arguments);
}
//now, if you want to let derived classes to raise events...
protected void OnSomeEvent3(Same Parameters As MapChangedEventHandler)
{
if (SomeEvent3 != null) SomeEvent3(parameters);
}
}
In this code I noticed the .Notify method is an extension method. Why and what is the code behind this method?
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
(...)
public void NotifyPropertyChanged(Expression<Func<object>> property)
{
this.PropertyChanged.Notify(property);
}
}
This extension method isn't provided by the .NET framework. Therefore, it is a custom extension method created somewhere in your code. To know what exactly it does, navigate to it and look at the source code (F12).
Generally speaking, I assume it will raise the PropertyChanged event with the property name extracted from the expression that is passed to it.
INotifyPropertyChanged interface is used to specify to subscribed clients that value of the property has been changed. To implement it, you have to declare a PropertyChanged event.
.Notify as you have mentioned is an extension method. The soul purpose of this .Notify must be to raise this event.
Internally it must be raising the event by doing something like this
PropertyChanged(this, new PropertyChangedEventArgs(info));
For more information look at MSDN
I ran across this pattern in the code of a library I'm using. It sets state within the event raising method, but only if the event is not null.
protected virtual void OnMyEvent(EventArgs e)
{
if(MyEvent != null)
{
EnsureChildControls();
MyEvent(this,e);
}
}
Which means that the state is not set when overriding the method:
protected override void OnMyEvent(EventArgs e)
{
base.OnMyEvent(e);
Debug.Assert( /* Child controls ensured */); // This fails
}
but is only set when handling the event:
foo.MyEvent += (o, args) => Debug.Assert(/* Child controls ensured */); // This passes
Setting state within the if(MyEvent != null) seems like bad form, but I've checked the Event Design Guidelines and it doesn't mention this.
Do you think this code is incorrect? If so, why? (Reference to design guidelines would be helpful).
Edit for Context:
It's a Control, I'm trying to create subclass of it, and the state that it's setting is calling EnsureChildControls() conditionally based upon there being an event handler. I can call EnsureChildControls() myself, but I consider that something of a hack.
I doubt you'll find any guidelines on something like this. Guidelines are typically for extremely common occurrences (which I wouldn't consider this).
Regarding the practice itself: I don't see any problem with doing it this way.
For what it's worth, you can avoid if(MyEvent != null) if you use this:
// initialize with empty delegate so MyEvent will never == null
public event MyEventHandler MyEvent = delegate {};
This answer provides an MSDN quote that answers my question:
When should you override OnEvent as opposed to subscribing to the event when inheritting
The protected OnEventName method also
allows derived classes to override the
event without attaching a delegate to
it. A derived class must always call
the OnEventName method of the base
class to ensure that registered
delegates receive the event.
I have seen developers using the below codes quite alternatively. What is the exact difference between these, and which ones go by the standard? Are they same, as Action and Func<T> is a delegate as well:
public event Action<EmployeeEventAgs> OnLeave;
public void Leave()
{
OnLeave(new EmployeeEventAgs(this.ID));
}
VS
public delegate void GoOnLeave(EmployeeEventAgs e);
public event GoOnLeave OnLeave;
public void Leave()
{
OnLeave(new EmployeeEventAgs(this.ID));
}
Fwiw, neither example uses standard .NET conventions. The EventHandler<T> generic should declare the event:
public event EventHandler<EmployeeEventArgs> Leave;
The "On" prefix should be reserved for a protected method that raises the event:
protected virtual void OnLeave(EmployeeEventArgs e) {
var handler = Leave;
if (handler != null) handler(this, e);
}
You don't have to do it this way, but anybody will instantly recognize the pattern, understand your code and know how to use and customize it.
And it has the great advantage of not being forced to choose between a custom delegate declaration and Action<>, EventHandler<> is the best way. Which answers your question.
The following two lines of code are almost equivalent:
public event Action<EmployeeEventAgs> Leave;
compared to:
public event EventHandler<EmployeeEventAgs> Leave;
The difference is in the signature of the event handler method. If you use the first approach with the action, you could have:
public void LeaveHandler(EmployeeEventAgs e) { ... }
and then this:
obj.Leave += LeaveHandler;
With the second approach, the signature of the LeaveHandler needs to be different:
public void LeaveHandler(object sender, EmployeeEventAgs e) { ... }
It is very important to notice that in both cases the event keyword is used to declare the event member. An event member declared this way is not simply a field of the class, despite it looks as if it was. Instead, the compiler creates it as an event property1. The event properties are similar to regular properties, except that they do not have get or set accessors. The compiler allows them to be used only on the left side of a += and -= assignments (adding or removing an event handler). There is no way to overwrite the already assigned event handlers, or to invoke the event outside the class that declares it.
If the event keyword was missing in both examples, you could do the following operations with no error or warning:
obj.Leave = LeaveHandler;
which will erase any registered handlers and replace them withe the LeaveHandler.
In addition, you can also perform this call:
obj.Leave(new EmployeeEventAgs());
The two situations above are considered an anti-pattern, if you intend to create an event. An event should be invoked only by the owner object and should not allow for untraceable removal of subscribers. The event keyword is the .NET's programmatic construct that helps you stick with the correct use of events.
Having the above in mind, I believe many people stick to the EventHandler approach because it is more unlikely to use an EventHandler without the event keyword. Actions have wider scope of usage, they do not look as naturally when used as events. The latter is, of course, a personal opinion, as the event handler approach has probably become too hardwired in my own coding practices. Still, if actions are used properly, it is not a crime to use them for events.
1 An event property is what the compiler automatically generates when seeing code like this:
event EventHandler SomeEvent
It becomes roughly the same code as the following:
private EventHandler _someEvent; // notice the lack of the event keyword!
public event EventHandler SomeEvent
{
add { _someEvent += value; }
remove { _someEvent -= value; }
}
Event invocations which we write as this:
this.SomeEvent(sender, args);
are converted into this:
this._someEvent(sender, args);
Action<T> is exactly the same as delegate void ... (T t)
Func<T> is exactly the same as delegate T ... ()
Action is just a shortcut for the full delegate declaration.
public delegate void Action<T>(T obj)
http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
Which one to use would depend on your organizations coding standards/style.
Yes, Action and Func are simply convenience delegates that have been defined in the 3.5 clr.
Action, Func and lambdas are all just syntactical sugar and convenience for using delegates.
There is nothing magic about them. Several people have written simple 2.0 addon libraries to add this functionality to 2.0 code.
You may want to look here, seeing what the compiler actually generates for Action is the best description. There's no functional difference in what you wrote, just shorter, more convenient syntax.
In general, they are equivalent. But in the context of using a delegate for the type of an event, the convention is to use EventHandler (where T inherits EventArgs):
public event EventHandler<EmployeeEventArgs> Left;
public void Leave()
{
OnLeft(this.ID);
}
protected virtual void OnLeft(int id)
{
if (Left != null) {
Left(new EmployeeEventArgs(id));
}
}
You could have written these Action and Func generic delegates yourself, but since they're generally useful they wrote them for you and stuck them in .Net libraries.
I've been trying to learn about events/delegates, but am confused about the relationship between the two. I know that delegates allow you to invoke different functions without needing to know what particular function is being invoked. (eg: a graphing function needs to accept inputs that are different functions to be graphed).
But I don't see how delegates are used in Events.
Can someone construct a simple example (in pseudocode or C# or Java) that illustrates the workings of Delegates as related to Events?
Thanks!
(This is all from a C# perspective.)
I have an article about the differences between events and delegates. That covers everything mentioned below in a lot more detail.
Basically I like to think of an event as being like a property - it's a pair of methods, that's all. Instead of get/set, an event has add/remove - meaning "add this event handler" and "remove this event handler". At the core, that's all an event is.
C# also has field-like events which are a shortcut:
public event EventHandler Foo;
declares both a field and an event, with a nearly trivial add/remove implementation. Within the class, referring to Foo refers to the field. Outside the class, referring to Foo refers to the event.
The basic idea is that an event allows other code to subscribe to and unsubscribe from it, by passing in a delegate (the event handler). Usually, subscription is implemented by creating a new multicast delegate containing the previous list of event handlers and the new one. So if you're storing the event handlers in a field called myEventHandlers, the subscription implementation might be:
myEventHandlers += value;
Similarly unsubscription usually involves creating a new multicast delegate without the specified handler:
myEventHandlers -= value;
Then when you want to raise/fire the event, you just call that multicast delegate - usually with a nullity check to avoid an exception being thrown if no-one has subscribed:
EventHandler handler = myEventHandlers;
if (handler != null)
{
// You could pass in a different "sender" and "args" of course
handler(this, EventArgs.Empty);
}
Using events, the subscribers don't know about each other, and can't raise the event themselves (usually). In other words, it's a pattern of encapsulation, which has been given status within both the language and the platform.
You'll need to be specific as to which language you want. As far as I know, Java doesn't have a concept of delegates (though I could be completely wrong); it tends to follow an observer pattern for event handling.
C#, however, does. An event in C# has the same relation to a delegate as a property has to its backing field. The delegate itself is what stores the pointer to the function that handles the event (or, more accurately, the list of pointers attached to the event; I use the term "pointer" loosely here).
If I declare this in C#:
public event EventHandler MyEvent;
And call the event like this:
MyEvent(this, EventArgs.Empty);
It's really just some shorthand for a full event implementation:
private EventHandler myEventHandler;
public event EventHandler MyEvent
{
add { myEventHandler += value; }
remove { myEventHandler -= value; }
}
And calling it...
myEventHandler(this, EventArgs.Empty);
All this is to say that an actual event exposes two operations: add and remove that are used by the consuming code to attach their event handlers to the event. In the default (shorthand) notation, the compiler creates a private instance member of the delegate type and uses it in the way that I described above. When you "invoke" the event, the compiler actually substitutes the name of the event for the name of the private backing delegate it created. This is why you can't invoke an event from a subclass--if the event is created in shorthand, then the backing member is private.
Difference is simple.
delegate is a class with two fields - object and MethodInfo.
event is a private field of type delegate and two public methods add and remove.
Usually under the hood of event MulticastDelegate is used - it's a class inherited from Delegate and containing list of Delegates. This allows event to have multiple subscribers.
You can look at:
http://msdn.microsoft.com/en-us/library/17sde2xt.aspx
The example is continued here:
http://msdn.microsoft.com/en-us/library/xwbwks95.aspx
Basically, as was mentioned, events are just special cases of delegates, but with the changes in .NET 3.5 you can write events without using delegates, though under the hood delegates are still written.
If you look at this article, they show how to use lambda expressions and anonymous functions for events:
http://msdn.microsoft.com/en-us/library/ms366768.aspx
.Net events are just delegates under the hood: They provide some syntactic sugar in the compiler.
You can set/reset a delegate, but you can only add or remove an event handler. The rationale is that you won't care who else subscribes to an event whereas plain delegates are more used in a "callback" scenario.
But at the end of all things they are very very similar.
Some resources:
C# events vs. delegates
Delegates & Events - A short Q&A
I'm new to the java world but I have to admit I'm pretty delighted, but I still miss some C # stuff, so design this pattern that has given me good results, Java experts see some drawback in using this pattern? It only supports java 8:
#FunctionalInterface
public interface IEvent<TEventArgs extends Object> {
void invoke(TEventArgs eventArgs);
}
public class EventHandler<TEventArgs>
{
private ArrayList<IEvent<TEventArgs>> eventDelegateArray = new ArrayList<>();
public void subscribe(IEvent<TEventArgs> methodReference)
{
eventDelegateArray.add(methodReference);
}
public void unSubscribe(IEvent<TEventArgs> methodReference)
{
eventDelegateArray.remove(methodReference);
}
public void invoke(TEventArgs eventArgs)
{
if (eventDelegateArray.size()>0)
eventDelegateArray.forEach(p -> p.invoke(eventArgs));
}
}
public class DummyEventProducer
{
// The event
public EventHandler<String> myEvent = new EventHandler<>();
public void onMyEvent(String A)
{
myEvent.invoke(A);
}
}
public class DummySubscriber {
// The method will be subscribed to the event
public void methodCallWhenEventGetTriggered(String eventArgs)
{
System.out.println("event fired with eventargs: " + eventArgs);
}
}
public class Main {
public static void main(String[] args)
{
// A dummy producer
DummyEventProducer producer = new DummyEventProducer();
// A dummy subscribers
DummySubscriber testingInstanceA = new DummySubscriber();
DummySubscriber testingInstanceB = new DummySubscriber();
DummySubscriber testingInstanceC = new DummySubscriber();
// We create decoupled event links because we want to un-subscribe later
IEvent<String> EventSink1 = testingInstanceA::methodCallWhenEventGetTriggered;
IEvent<String> EventSink2 = testingInstanceB::methodCallWhenEventGetTriggered;
IEvent<String> EventSink3 = testingInstanceC::methodCallWhenEventGetTriggered;
// subscribe to the event on dummy producer
producer.myEvent.subscribe(EventSink1);
producer.myEvent.subscribe(EventSink2);
producer.myEvent.subscribe(EventSink3);
// fire the event on producer
producer.onMyEvent("Hola MUNDO with decoupled subscriptions!");
// unsubscribe to the event on dummy producer
producer.myEvent.unSubscribe(EventSink1);
producer.myEvent.unSubscribe(EventSink2);
producer.myEvent.unSubscribe(EventSink3);
// fire the event on producer again
producer.onMyEvent("Hola MUNDO! with no events subscriptions :(");
// IF YOU DON CARE ABOUT UNSUBSCRIBE YOU CAN LINK EVENTS DIRECTLY TO THE SUBSCRIBER
producer.myEvent.subscribe(testingInstanceA::methodCallWhenEventGetTriggered);
producer.myEvent.subscribe(testingInstanceB::methodCallWhenEventGetTriggered);
producer.myEvent.subscribe(testingInstanceC::methodCallWhenEventGetTriggered);
// fire the event on producer again
producer.onMyEvent("Hola MUNDO! with strong link subscriptions (cannot be un-subscribed");
}
}
Feel free to ask, corrections, suggestions =)
Best regards!