I am surprised how often C# developers are confused about delegates and occasions. They sometimes neglect how all C# occasions are primarily based on delegates and what the delegates offer for C# events. As well, some are confused about learn how to publish and subscribe to events and tips on how to move information when elevating an event from a publisher to subscriber.
On this C# event tutorial, I will explain how delegates are the foundation for C# events and show the 2 main delegates that Microsoft has given us for creating our personal events. I can even present you the way to subscribe to your individual events and even move knowledge back to the occasion handlers.
Every single occasion in .Net, whether Microsoft created it or if it was created by another person, is predicated on a .Net delegate. Delegates are one of the 5 varieties of sorts included with .Net - class, structure, interface, enumeration, and delegate. At its foundation, delegates do two issues:
1. When created, it points to a way (instance or static) in a container (class or construction). For occasions, it factors to an event hander method. 2. It defines exactly the type of strategies that it could point to, including the quantity and sorts of parameters and likewise the return sort.
Here is a definition of a simple delegate. It may be declared on the namespace stage, meaning it doesn’t need to be nested in a category. The delegate under can solely point to a way that accepts two integer parameters and returns an integer. Interestingly, the parameters “a” and “b” are never used immediately however they're required to outline the delegate.
You'll be able to create an occasion of the delegate pointing to a way. Then, each time you name the delegate, it calls the method for you. If the method returns a price, the delegate returns it for you. Here’s an entire easy instance.
As useless and redundant because the code seems, delegates will be set at run time rather than design time. This adds flexibility to our code. We can assign methods as our app is operating primarily based on current variable values. For events, we will dynamically subscribe and unsubscribe to events with occasion handler strategies.
Let’s assume we want to raise an occasion within the Adder class if the sum of the two numbers in Add() is a multiple of five (5). We are able to outline an occasion primarily based on the delegate. This occasion can be used to boost a notification to run event handlers assigned to it.
Note: All C# occasions in .Net are based on delegates. Note: Wherever you need to raise an event, you will need to additionally define the occasion.
Note: You should never elevate (publish) an event unless at least one object is listening (subscribing) to the event. In different words, the occasion should not equal null.
Note: A Microsoft Best Practice: All events must be outlined beginning with the phrase “On”. This code solely raises the C# occasion if there may be any code subscribing to it. Let’s modify the code by eradicating the easy delegate and have it subscribe to the event.
When run, here is the result: This code creates a brand new instance of the dgEventRaiser delegate that factors to the brand new technique called a_MultipleOfFiveReached. The += operator is used to guard different strategies that will have already subscribed to the occasion.
Microsoft made it simpler for us to subscribe to C# events. The long line of code above will be shortened to the following snippet with the identical impact.
This code works advantageous but the code within the Adder class is extra complex than it must be. Microsoft has included two (2) major delegates that we are able to use when defining occasions. These delegates are used all over the place within the framework and may be easier to use due to their constant sample.
Listed here are the two constructed-in delegates: The primary delegate is used merely to raise a notification, an occasion signifying that one thing occurred. The second delegate permits you to return a number of values to the event handler method. It requires you to create an instance of a category that derives from the EventArgs class.
To switch our code to make use of the primary constructed-in delegate, we are able to delete our delegate and change our C# occasion to use the EventHandler delegate. After we increase the event, we must follow along with the delegate definition and go within the required parameter values. Note how we cross our current occasion of adder for the primary parameter (sender) and since we're not passing back any event arguments, we use EventArgs.Empty for “e”.
C# tutorial had to alter our occasion handler technique to observe the pattern of the delegate with (object sender, EventArgs e).
In order to use the opposite delegate and cross the grand whole again to the event hander method, we first must outline a customized class known as MultipleOfFiveEventArgs for passing back a custom value, equivalent to Total. It must inherit from the EventArgs class.
Then we might want to outline our occasion to make use of the other generic delegate which incorporates the custom EventArgs type, MultipleOfFiveEventArgs. We must additionally change how we increase the event. Finally, we modify the occasion handler technique to match the delegate. Here is the complete code:
I hope this C# events tutorial has been useful for you in learning delegates and events. Best wishes and completely happy programming!