Delegates are useful to implement function pointers or
callbacks. Here are the basics of a delegate: Defining a delegate lets you
invoke other functions that match the definition of the delegate. Right – what
does that mean?
First off, a delegate is really a class. It derives from System.Delegate
(really, it could also derive from System.MulticastDelegate, but we’re
trying to keep thing simple here). So, you can define a delegate and then call
it like a method. See Listing 1.
Listing 1 – Define a delegate
Public delegate bool CookDinner(string MainCourse);
So, what does this get you? First notice that the delegate
looks like a method definition with a return type and method parameters. That
should feel pretty comfortable. But, like I mentioned above, this is actually
getting created as a class, so under the hood it is much more than a method.
Now that we have this delegate defined we can use set it up for use. See
Listing 2 – Setup the delegate
CookDinner cook = new CookDinner(CookingTacos);
Private bool CookingTacos(string Meat)
if(Meat != “vegetable”)
Note that when we initialize the instance of our delegate, CookDinner,
with the variable cook we are passing in a method that matches the delegate’s
definition to the constructor. This is very important. All it takes to
instantiate an instance of the delegate is a logical pointer to a method. Now
take a look at Listing 3 and you’ll see how the delegate is used.
Listing 3 – Use the delegate
FeedTheFamily(cook); //pass in the delegate
Private void FeedTheFamily(CookDinner cookIt)
This helps us decouple a specific action from each method.
Here, we can pass in our delegate to FeedTheFamily and that method is
then able to call the method we already defined. So now if we decide that
FeedTheFamily needs to cook something else, we change the method that is passed
in the CookDinner constructor.