Thursday, January 24, 2019

Evens and Delegates in C#

A nice article describes the events and delegates in http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified. Here I give a summary of using events and delegates in C#.


A delegate is a class, it's just a function pointer.


  • Every delegate has a signature, for example: Delegate int MyDelegate(string s, bool b);
  • Consider the following function: private int MyFunc1(string str, bool boo) { ... }
  • You can pass a function and register: var md = new MyDelegate(MyFunc1);
  • Then use the registered function: md("mystring", true);

An event is a message sent by an object to signal the occurrence of an action. 

  • The action could be caused by user interaction such as a button click, or it could be raised by some other program logic, such as changing a property’s value.


No comments:

Followers