C# Delegates Explained - Delegates on Instance Methods
(Page 3 of 5 )
Copy the following code and paste it in your VS.NET class file
using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);
public void Add(int first, int second)
{
Console.WriteLine("The method Add() returns {0}", first + second);
}
public void Multiply(int first, int second)
{
Console.WriteLine("The method Multiply() returns {0}", first * second);
}
public void Divide(int first, int second)
{
Console.WriteLine("The method Divide() returns {0}", first / second);
}
}
public class DelegateApp
{
public static void Main()
{
Math math = new Math();
Math.DelegateToMethod aDelegate = new Math.DelegateToMethod(math.Add);
Math.DelegateToMethod mDelegate = new Math.DelegateToMethod(math.Multiply);
Math.DelegateToMethod dDelegate = new Math.DelegateToMethod(math.Divide);
aDelegate(5,5);
mDelegate(5,5);
dDelegate(5,5);
Console.ReadLine();
}
}
}

I have made some changes to the example so let's go through them. First I have defined the delegate type as a nest type to the Math class. This is perfectly valid but you have to qualify the name of the delegate with the class name, so we write Math.DelegateToMethod.
I have changed the signature of the delegate so it returns void instead of int. I had to change the signature of the methods of the Math class to return void. I also removed the static keyword.
In the Main method of the class DelegateApp I created an object of the Math class, then I created the three delegate objects, but this time I passed an instance method (not a static method). I called the delegate and passed 5, 5 as the parameters.
I think by now you understand the mechanism of how delegates work, but you don't understand why it's useful or how we can use them efficiently. Just wait until the next article (C# Events) and you will appreciate the use of delegates. Now let's discuss multicast delegates.
Next: Multicast Delegates >>
More C# Articles
More By Michael Youssef