Last active
April 6, 2016 10:13
-
-
Save snmslavk/20069de476c284a88b0ac899b83e5833 to your computer and use it in GitHub Desktop.
Events and delegates
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
public class SampleEventArgs | |
{ | |
public SampleEventArgs(string s) { Text = s; } | |
public String Text { get; private set; } // readonly | |
} | |
public class Publisher | |
{ | |
//Sample delegate | |
public delegate void SampleEventHandler(object sender, SampleEventArgs e); | |
//GenericDelegate | |
public delegate T GenericEventHandler<T>(); | |
public event Func<bool> SampleEventWithReturnValue; | |
public event SampleEventHandler SampleEvent; | |
public virtual void RaiseSampleEvent() | |
{ | |
if (SampleEvent != null) | |
SampleEvent(this, new SampleEventArgs("Hello")); | |
} | |
//When multiple handlers are associated with a single event in C# and the handler signature has a return type, | |
//then the value returned by the last handler executed will be the one returned to the event raiser. | |
public virtual bool RaiseSampleEventWithReturnValue() | |
{ | |
return SampleEventWithReturnValue(); | |
} | |
} | |
class Program | |
{ | |
public static void Main() | |
{ | |
var zz = new Publisher(); | |
zz.SampleEvent += (object sender, SampleEventArgs e) => { Console.WriteLine(e.Text); }; | |
zz.RaiseSampleEvent(); | |
//Output: Hello | |
zz.SampleEventWithReturnValue += () => { return true; }; | |
zz.SampleEventWithReturnValue += () => { return true; }; | |
zz.SampleEventWithReturnValue += () => { return false; }; | |
Console.WriteLine(zz.RaiseSampleEventWithReturnValue()); | |
//Output: False | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment