Personal notes on software development.
For Java technologies check my dedicated site

Pages

Delegates are used to hook up an event to a method that will handle that event (in fact, events themselves  are just a restricted kind of delegate). Using a delegate you can encapsulate any matching method that has the the same signature (same parameters) and return type. They are ideal for:

  • event handling: “Call this method when this event happens”;
  • callbacks: “Call this method when you’re done doing this work”;
In short, delegates decouple the class that declares the delegate from the class that uses the delegate: that is, the creator of the Button does not need to know how the Button will be used in every program that places a button on the page. Another example,using a delegate a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.


The signature of a single cast delegate is shown below:
public delegate int ButtonClickHandler (object obj1, object obj2)
This declaration defines a delegate named ButtonClickHandler, which will encapsulate any method that takes two objects as parameters and returns an int.


Related articles:


No comments:

Post a Comment