SoFunction
Updated on 2025-03-07

C# event usage

Events are based on delegates and can provide a publish/subscribe mechanism for any delegate type.
Use the event keyword to define a delegate type as an event.
The following is an example to introduce the event:

// Event Publishing Class        public class PublishEvent
        {
            public delegate string Display(string str);
            public event Display DisplayEvent;

            //The client code triggers the event by calling this method            public void Shows(string str)
            {
                if (DisplayEvent != null)
                {
                    DisplayEvent(str);
                }
            }

        }

        //Event listening class, this class subscribes to events        public class Listen1
        {
            public string MakeAlert(string str)
            {
                (str + "Listen1");
                return str + "Listen1";
            }
        }
        public class Listen2
        {
            public string ShowMsg(string str)
            {
                (str + "Listen2");
                return str + "Listen2";
            }
        }

Client code:

class Program
        {
            static void Main()
            {
                PublishEvent pe = new PublishEvent();
                Listen1 l1 =  new Listen1();
                Listen2 l2 = new Listen2();

                //Variables l1 and l2 subscribe to events                 += ;
                 += ;

                //Trigger event                ("event");

                ();

            }
        }

An event is a special commission (https:///article/), it is a dedicated delegate used for event-driven model. You can call the delegate directly in the client code to trigger the function pointed to by the delegate, but events cannot, and the triggering of the event can only be triggered by the service code itself. In other words, in your code, you can not only arrange which function is called, but also directly call it. Events cannot be called directly and can only be triggered through certain operations. In addition to this, events have all the functions of delegate, including multicast features. That is, events can have multiple event handling functions, and the delegate can also be a multicast delegate.
Events are encapsulated delegate instances; delegate is type, event is instances!
EventHandler<TEventArgs>.NET comes with delegate, which is also used to define events.

This is all about this article about the usage of C# events. I hope it will be helpful to everyone's learning and I hope everyone will support me more.