Created
April 20, 2013 06:10
-
-
Save jonfriesen/5424952 to your computer and use it in GitHub Desktop.
Playing with events and delegates. I'm having difficulty wrapping my head around the entire concept... From what I gathered everything revolves around the delegate concept. Events reference the delegate as the type, and when they are triggered they must use the same parameters that the delegate has. The delegate links the event to the code that …
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
delegate void TaskUpdateHandler(object sender, EventArgs e); // Why does this have to be outside of the namespace? | |
namespace DelegatesEventsLambda | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
JonsTask jt = new JonsTask("Write more code"); | |
// Ways of reading the event | |
// Lambda (newest from .net 3) | |
jt.TaskUpdated += (sender, e) => Console.WriteLine(sender.GetType().ToString() + " with contents: " + (((JonsTask)sender).task)); | |
//Anonymoose delegate (second newest from .net 2) | |
jt.TaskUpdated += delegate(object sender, EventArgs e) { Console.WriteLine(sender.GetType().ToString() + " with contents: " + (((JonsTask)sender).task)); }; | |
//deletegate (oldest, huge, excessive code) | |
TaskUpdateHandler ct = new TaskUpdateHandler(OutputEventStuff); // So i have to create a new TaskUpdateHandler and assign it to the corresponding methid | |
jt.TaskUpdated += ct; | |
jt.task = "Go to bed"; | |
Console.WriteLine("Press Any Key..."); | |
Console.ReadKey(false); | |
} | |
static void OutputEventStuff(object sender, EventArgs e) // This method must have same params as the delegate so it can receive the objects from the events? | |
{ | |
Console.WriteLine(sender.GetType().ToString() + " with contents: " + (((JonsTask)sender).task)); | |
} | |
} | |
class JonsTask | |
{ | |
public event TaskUpdateHandler TaskUpdated; // The event type has to be the same as the delegate from what I can see | |
private string t; | |
public JonsTask(string s) | |
{ | |
this.task = s; | |
} | |
public string task | |
{ | |
get { return t; } | |
set | |
{ | |
if (this.t != value) | |
{ | |
this.t = value; | |
if (TaskUpdated != null) | |
{ | |
TaskUpdated(this, EventArgs.Empty); // The event call params must match the delegates | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment