Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Thursday, July 23, 2009
Delegates, delegate to another method.  In this example, depending on which person is wired up - Suzanne or Amy.. depends on which method is called when the Get the ingredient button is called.


source code here..delegateIngredients.zip (91.58 KB)






    // can be used to create a variable that can point to any method that takes an int parameter and returns a string
    public delegate string GetSecretIngredient(int amount);

On the form:
        // so variable ingredientMethod of type delegate GetSecretIngredient currently points to a null method
        GetSecretIngredient ingredientMethod = null;
        private void getSuzanne_Click(object sender, EventArgs e)
        {
            // suzanne.MySecretIngredientMethod property returns a new instance of the the GetSecretIngredient delegate thats
            // pointing to her secret ingredient method.
            ingredientMethod = new GetSecretIngredient(suzanne.MySecretIngredientMethod);
        }
When button is pressed it will go to either the suzanne.MySecretIngredientMethod or the amy.AmySecretIngredientMethod
        private void useIngredient_Click(object sender, EventArgs e)
        {
            if (ingredientMethod != null)
                Console.WriteLine("I'll add " + ingredientMethod((int)amount.Value));
            else
                Console.WriteLine("I dont have a secret ingredient");
        }
Good duck example here:
http://stackoverflow.com/questions/687626/the-purpose-of-delegates



All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview