English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I read a brief rundown about delegates in a programming book and can't think of a real world use for them. Can anyone help me?

2006-12-27 07:30:21 · 1 answers · asked by eclstate 2 in Computers & Internet Programming & Design

1 answers

A delegate is useful when you know you want to invoke a method, but you can't know which method you will be invoking until runtime.

For example, lets say you have a very generic method called CleanUpPage. You have lots of different pages that do different things, but they all need to call this method when they are finished. Finally, lets also say that when CleanUpPage is done, the page that called it needs to run another function, but since each page is different, each page needs a *different* function to run. The easiest solution is to use a delegate.

A delegate is a way to pass a reference to a method just like you would pass a string or some other object. So we could pass a *reference* to a specific method right into CleanUpPage(). So on a particular page, you would say:

public delegate void CleanUpDelegate();

public void SpecialMethodJustForThisPage()
{
}

CleanUpDelegate myDel = new CleanUpDelegate(SpecialMethodJustForThisPage);

CleanUpPage(myDel);

Now, CleanUpPage can invoke the delegate, which contains a reference to the specific function you want to use.

Delegates are most useful when writing your own events, because events do not know *which* method will be invoked, only that methods *can* be invoked. You declare which method to invoke elsewhere outside of the event declaration, by using delegates.

2006-12-27 11:15:11 · answer #1 · answered by Rex M 6 · 0 0

fedest.com, questions and answers