What is the difference between events and delegates in c




















Events notify that some action has been performed. The basic difference between delegates and events is that delegates hold the reference of the methods and event provides a way to access that method using delegates. The event is an over-layered abstraction provided to the delegates.

Declaration A delegate is declared outside any class. An event is declared inside a class. Invoke To invoke a method it has to be referred to the delegate. To invoke a method it has to be assigned to the event. Covariance and Contravariance They provide flexibility to the delegates. No such concept. Event Accessor No such concept.

Manages the list of the event handlers. Dependency Delegates are independent of events. The event can not be created without delegates. In C delegates are used as a function pointer to refer a method.

It is specifically an object that refers to a method that is assigned to it. The same delegate can be used to refer different methods, as it is capable of holding the reference of different methods but, one at a time. Which method will be invoked by the delegate is determined at the runtime.

The syntax of declaring a delegate is as follow:. Example with Delegates in this case, an Action - that is a kind of delegate that doesn't return a value. Another weak spot is that every class which uses your Animal class can invoke the delegate directly. For example, animal. Run or animal. Invoke are valid outside the Animal class. The sender is null if it comes from static methods. Refer here for documentation about EventHandler. Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

Events represent They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing. Even if they were exactly the same thing syntactically and in the IL code there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way which doesn't mean I like to have the same code twice.

Here is another good link to refer to. How would another class subscribe to an event? Three options:. Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance. In addition, you still need to write the properties. Option 3 is basically what events give you, but with a guaranteed convention generated by the compiler and backed by extra flags in the IL and a "free" implementation if you're happy with the semantics that field-like events give you.

Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription. What a great misunderstanding between events and delegates!!! And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate.

Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.

However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C , you are free to choose the way you store the event handlers note that event handlers are instances of the type of the event , which in turn is mandatorily a delegate type from the previous Observation.

But, you can store those event handlers which are delegate instances in a data structure such as a List or a Dictionary or any other else, or even in a backing delegate field. It always helps me to have a simple, concrete example.

So here's one for the community. First I show how you can use delegates alone to do what Events do for us. Then I show how the same solution would work with an instance of EventHandler. This post was inspired by an article by John Skeet.

Suppose I have a WinForms app with a single drop-down box. On the main form is a custom user control that shows the properties of that person. When someone selects a person in the drop-down the labels in the user control update to show the properties of the person selected. Finally we have the following code in our Form1. Here we are Calling OnPersonChanged, which calls any code subscribed to the delegate.

So that's how you would get this working without using events and just using delegates. We just put a public delegate into a class -- you can make it static or a singleton, or whatever.

Because public fields are bad for many, many reason. So what are our options? As John Skeet describes, here are our options:. This third option is essentially what an event gives us. Let's see what the same program looks like, but now using an Event instead of the public delegate I've also changed our Mediator to a singleton :. Notice that if you F12 on the EventHandler, it will show you the definition is just a generic-ified delegate with the extra "sender" object:.

Because the EventHandler wants and EventArgs as a parameter, I created this class with just a single property in it:. Hopefully that shows you a bit about why we have events and how they are different -- but functionally the same -- as delegates. An event in. Both C and vb. Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so.

From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in. Above two are the weak points for delegates and it is addressed in event. Delegate is a type-safe function pointer. Event is an implementation of publisher-subscriber design pattern using delegate.

Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime. Delegates can call methods synchronously and asynchronously. The delegate contains a couple of useful fields. The first one holds a reference to an object, and the second holds a method pointer. When you invoke the delegate, the instance method is called on the contained reference. However, if the object reference is null then the runtime understands this to mean that the method is a static method.

Moreover, invoking a delegate syntactically is the exact same as calling a regular function. Therefore, delegates are perfect for implementing callbacks. A delegate is a solution for situations in which you want to pass methods around to other methods. You are so accustomed to passing data to methods as parameters that the idea of passing methods as an argument instead of data might sound a little strange.

However, there are cases in which you have a method that does something, for instance, invoking some other method. You do not know at compile time what this second methods is. That information is available only at runtime hence Delegates are the device to overcome such complications.

Here, we are defining the delegate as a delegate type. The important point to remember is that the signature of the function reference by the delegate must match the delegate signature as:. In this code, you instantiate an array of Delop delegates. Each element of the array is initialized to refer to a different operation implemented by the operation class. Then, you loop through the array, apply each operation to three different values.

After compiling this code, the output will be as follows;. The anonymous methods reduce the complexity of code, especially where there are several events defined. With the anonymous method, the code does not perform faster. The compiler still defines methods implicitly. The code above combines two delegates that hold the functions Add and Square. Here the Add method executes first and Square later.



0コメント

  • 1000 / 1000