Delegates and events

Delegate:
Normally funtions we called in oop's by object of the class.so each time fuction stack will creats and execute that function so each time memory will allocates for this exection..so memory will be wasting here., so to resolve this problem Delegate is came Actually,
Delegate is a function pointer it creates funtion stack and exucutes the functions on a same memory location(number of times you called also).so no separate memory allocation is required each and every time to call a same function..Delegates takes funtion as an argument.

Event:
Event is an action ,it runs on a perticular time only..for example:when button click,mouseoveron like

So finally we considerd as events and delgates are not comparible..


Methods are registered in Delegate and Delegates are registered in Events.

Event keyword provides a better layer of security than delegates.



delegate += f1;
delegate += f2;
delegate = f3 ;// this wipes out the earlier entries of f1 & f2.

This is not possible while using event keyword and the compiler will throw an error.

event = f3; // not allowed
event =null; // not allowed
event (); //not allowed

We can not fire any event without delegate.

  • A Button is a class, when you click on it, the click event fires.
  • A Timer is a class, every millisecond a tick event fires.


Comments