Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "x.OnSpeak += (s, e)" mean?

Tags:

c#

events

  • I know that's the "e" for the event args, but what does "s" mean here and the "+= ( , ) =>" ?
  • 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));
       }
     }
    }
    
like image 754
Kinani Avatar asked Dec 05 '25 08:12

Kinani


1 Answers

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!");
}
like image 174
Grant Winney Avatar answered Dec 07 '25 21:12

Grant Winney