Home | Applications | Documentation | Transport | Personal |

Documentation

Home | Cloud | C# | Database | DevOps | Revision | Web |

C# | API | Delegates | Dll | Garbage | Events | Interfaces | Lambdas | MVC | NoSql | Objects | Tasks | Worker |

C# Events

Events

Events and EventHandlers are for sending information between methods in an application which are encapsulated. You have subscribers and publishers.

Define

First we need to define the event. See a basic defintion below.

            // Declare the event
            public event EventHandler ClickNumberEvent;
            
The return type in the event handler here is a string, but it can be anything.

Publish

We need to now publish this. i.e. Send it out for the listener to pick it up. So we need to check to see if a Listener exists "?" and if so, invoke the event.

            ClickNumberEvent?.Invoke(this, "1");
            
The two parameters of the event are, Sender object and Parameters.

Subscribe

Lastly, we need toc subscribe to the events. We need to listen for the events that are being published. See the code below.


            subScreen.ClickNumberEvent += M_ClickNumberEvent;

            private void M_ClickNumberEvent(object sender, string e)
            {
                txtNumber.Text += e.ToString();
            }
            
We are adding the event handler to the stack so that when the listener receives the event, it will run the attached code.
NOTE: You will need to remove the event before closing the program.
            subScreen.ClickNumberEvent -= M_ClickNumberEvent;