Super simple example for event delegate in C # .net?

I need a very simple example to understand myself about events. I find it very difficult to understand the examples available on the Internet or books.

+4
source share
5 answers

This is a simple implementation of a class that provides an event.

public class ChangeNotifier { // Local data private int num; // Ctor to assign data public ChangeNotifier(int number) { this.num = number; } // The event that can be subscribed to public event EventHandler NumberChanged; public int Number { get { return this.num; } set { // If the value has changed... if (this.num != value) { // Assign the new value to private storage this.num = value; // And raise the event if (this.NumberChanged != null) this.NumberChanged(this, EventArgs.Empty); } } } } 

This class can be used as follows:

 public void SomeMethod() { ChangeNotifier notifier = new ChangeNotifier(10); // Subscribe to the event and output the number when it fires. notifier.NumberChanged += (s, e) => Console.Writeline(notifier.Number.ToString()); notifier.Number = 10; // Does nothing, this is the same value notifier.Number = 20; // Outputs "20" because the event is raised and the lambda runs. } 

As for the control flow, execution of the flow in SomeMethod() . We create a new ChangeNotifier and call its constructor. This assigns a value of 10 to the private element num .

Then we subscribe to the event using the syntax += . This operator accepts a delegate on the right side (in our case, this delegate is a lambda) and adds it to the collection of delegates at the event. This operation does not execute the code that we wrote in ChangeNotifier . It can be configured using the add and remove methods on the event, if you want, but rarely need to do this.

Then we perform a couple of simple operations on the Number property. First we assign 10 , which runs the set method on the Number property with value = 10 . But the num member is already evaluated at 10 , so the initial conditional value is set to false and nothing happens.

Then we do the same with 20 . The value is different this time, so we assign a new value to num and fire the event. First, we verify that the event is not zero. It is zero if nothing has subscribed to it. If it is not null (that is, if something is subscribed to it), we start it using the standard method / delegate syntax. we just call the event with the event arguments. This will call all methods that subscribe to the event, including our lambda, which will execute Console.WriteLine() .


Henrik successfully fulfilled the potential race condition, which exists if one thread can be in the Number setter and the other listener unsubscribes. I do not consider this a common thing for those who do not yet understand how events work, but if you are concerned about this possibility, change these lines:

 if (this.NumberChanged != null) this.NumberChanged(this, EventArgs.Empty); 

will look something like this:

 var tmp = this.NumberChanged; if (tmp != null) tmp(this, EventArgs.Empty); 
+6
source share
 class Program { static void Main(string[] args) { Parent p = new Parent(); } } //////////////////////////////////////////// public delegate void DelegateName(string data); class Child { public event DelegateName delegateName; public void call() { delegateName("Narottam"); } } /////////////////////////////////////////// class Parent { public Parent() { Child c = new Child(); c.delegateName += new DelegateName(print); //or like this //c.delegateName += print; c.call(); } public void print(string name) { Console.WriteLine("yes we got the name : " + name); } } 
+2
source share
 Class A { public delegate void EventHandler(); public static event EventHandler workComplete(); void doWork(){ // DO WORK } void onWorkComplete(){ // Raise event workComplete(); } } Class Main { A a = new A(); a.workComplete += new () -> { // On Class Complete Work Console.WriteLine("Work Complete"); }; } 
+1
source share

If you have background C, you can see that the delegate is a function pointer.

0
source share

I struggled to understand the concept of delegate event in C #. I found a document on the Internet. The author explained the concept in a simple way. It helps me a lot, so I want to share: https://www.intertech.com/Blog/c-sharp-tutorial-understanding-c-events/

I have no idea about a writer and a webpage, but he or she made a good example! I have added a simple example below. In this example, I added a delegate and an event to the Multiplication class.

 class Program { static void Main(string[] args) { Multiplier mult = new Multiplier(); mult.OnResultReachedToTen += ResultReachedToTen; int iAnswer = mult.Multiply(5, 1); Console.WriteLine("iAnswer = {0}", iAnswer); iAnswer = mult.Multiply(5, 2); Console.WriteLine("iAnswer = {0}", iAnswer); Console.ReadKey(); } static void ResultReachedToTen() { Console.WriteLine("Result is reached to 10!"); } } public class Multiplier { public delegate void EventRaiser(); public event EventRaiser OnResultReachedToTen; public int Multiply(int a, int b) { int iResult = a * b; if (iResult == 10 && OnResultReachedToTen != null) { OnResultReachedToTen(); } return iResult; } } 
-one
source share

All Articles