Last active
May 28, 2016 17:45
-
-
Save jmsevold/c290cd6d528c3efb9db655d60f282178 to your computer and use it in GitHub Desktop.
The world's easiest event example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
We begin with a situation: | |
- We want code elsewhere to run when something occurs at a particular point in | |
our application. The class that contains this will be the publisher of the event. | |
Notice I am not using the word "event" to avoid confusion. | |
- In this case, it is the printing of a string, which we see occurs in the PrintString() method. For some reason, | |
we give a shit about this. | |
1. Declare a delegate. This is the contract between the publisher and subscriber(s). It's saying "Any and all methods- which we | |
will refer to as event handlers-that want to be run after this interesting occurrence must conform to this method signature" | |
2. Declare an Event of the type of delegate you previously declared. The Event will do two things: | |
- Store a list of the event handlers (the methods you want to be run after the event occurs), then call them. | |
- Wait to be called like a method, so it can do the above ^ | |
3. Create a method that is responsible for calling the event just like a method so the event can be raised. | |
Where should this method be called? Inside the method where our interesting event occurs. | |
4.Register the subscriber(s) with the Event. | |
publisher.EventName += subscriber.OnEventHappened; | |
5. Place the event call in it's proper place, and call it. In this example, this means placing the method that encapsulates | |
the event call at the end of the PrintString() method, then calling it. | |
*/ | |
using System; | |
namespace EventsAndDelegates | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var publisher = new Publisher(); | |
var subscriber = new Subscriber(); | |
publisher.StringPrinted += subscriber.OnStringPrinted; // 4 | |
publisher.PrintString("Hello"); // 5 | |
} | |
} | |
public class Publisher | |
{ | |
// 1 | |
public delegate void StringPrinterEventHandler(object source, EventArgs args); | |
//2 | |
public event StringPrinterEventHandler StringPrinted; | |
// 0 | |
public void PrintString(string str) | |
{ | |
Console.WriteLine(str); | |
OnStringPrinted(); | |
} | |
// 3 | |
protected virtual void OnStringPrinted() | |
{ | |
if (StringPrinted != null) { | |
StringPrinted(this,EventArgs.Empty); | |
} | |
} | |
} | |
public class Subscriber | |
{ | |
public void OnStringPrinted(object source, EventArgs e) | |
{ | |
Console.WriteLine("The Subscriber has been notified!"); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment