I need a very simple example to understand myself about the events.I am feeling very difficult to understand the examples available in internet or books.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is a simple implementation of a class that exposes an event.
This class may be used something like as follows:
Regarding control flow, execution flows into
SomeMethod(). We create a newChangeNotifierand thus call its constructor. This assigns the value of10to the privatenummember.We then subscribe to the event using the
+=syntax. This operator takes a delegate on the right hand side (in our case, that delegate is a lambda) and adds it to the collection of delegates on the event. This operation doesn’t execute any code that we’ve written in theChangeNotifier. It can be customized through theaddandremovemethods on the event if you’d like, but there’s rarely a need to do that.Then we perform a couple simple operations on the
Numberproperty. First we assign10, which runs thesetmethod on theNumberproperty withvalue = 10. But thenummember is already valued at10, so the initial conditional evaluates to false and nothing happens.Then we do the same thing with
20. This time the value is different, so we assign the new value tonumand fire the event. First we verify that the event is not null. It’s null if nothing has subscribed to it. If it’s not null (ie, if something is subscribed to it), we fire it using the standard method/delegate syntax. we simply call the event with the event’s arguments. This will call all methods that have subscribed to the event, including our lambda that will perform aConsole.WriteLine().Henrik has successfully nitpicked the potential race condition that exists if one thread can be in
Number‘s setter while another thread is unsubscribing a listener. I don’t consider that a common case for someone who doesn’t yet understand how events work, but if you’re concerned about that possibility, modify these lines:to be something like this: