Is there's any other alternative implementations ?
class Program
{
static void Main(string[] args)
{
var x = new Animal();
x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");
x.OnSpeak += (s, e) => Console.WriteLine(e.Cancel ? "Cancel" : "Do not cancel");
Console.WriteLine("Before");
Console.WriteLine(string.Empty);
x.Speak(true);
x.Speak(false);
Console.WriteLine(string.Empty);
Console.WriteLine("After");
Console.Read();
}
public class Animal
{
public event CancelEventHandler OnSpeak;
public void Speak(bool cancel)
{
OnSpeak(this, new CancelEventArgs(cancel));
}
}
}
This is often referred to as an "inline event", and is just another way of running particular code when the OnSpeak event fires.
x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");
The s is the sender, and the e is the event arguments.
You could rewrite your code like this, which may be more familiar-looking:
x.OnSpeak += OnSpeakEvent;
private static void OnSpeakEvent(object s, CancelEventArgs e)
{
Console.WriteLine("On Speak!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With