SoFunction
Updated on 2025-03-07

Detailed explanation of C# event accessor


//Declare a delegate
    delegate void EventHandler();

    class MyClass
    {
//Declare a member variable to save the event handle (delegate called when the event is fired)
        private EventHandler m_Handler = null;

//Inspire events
        public void FireAEvent()
        {
            if (m_Handler != null)
            {
                m_Handler();
            }
        }

//Declare the event
        public event EventHandler AEvent
        {
//Add accessor
            add
            {
//Note that the accessor actually contains an implicit parameter named value
//The value of this parameter is the delegate passed by the client program when calling +=
("AEvent add is called, the HashCode of value is:" + ());
                if (value != null)
                {
//Set the m_Handler domain to save the new handler
                    m_Handler = value;
                }
            }

//Delete the accessor
            remove
            {
("AEvent remove is called, the HashCode of value is:" + ());
                if (value == m_Handler)
                {
//Set m_Handler to null, the event will no longer be fired
                    m_Handler = null;
                }
            }

        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
//Create a delegation
            EventHandler MyHandler = new EventHandler(MyEventHandler);
            MyHandler += MyEventHandle2;
//Register the delegation to the event
            += MyHandler;
//Inspire events
            ();
//Revoke the delegation from the event
            -= MyHandler;
//Inspire the event again
            ();


            ();
        }

//Event Handler
        static void MyEventHandler()
        {
            ("This is a Event!");
        }

//Event Handler
        static void MyEventHandle2()
        {
            ("This is a Event2!");
        }
    }