In the last example, we saw how we can create an object of a delegate and pass the method name in the constructor. Now we will look at another way of achieving the same thing, but in an easier way. This is called method group conversion. Here, you don't need to initialize the delegate object, but you can directly assign the method to it. Let me show you an example:
using System;
namespace Delegate1
{
delegate int MathFunc(int a, int b);
class Program
{
static void Main(string[] args)
{
MathFunc mf = add;
Console.WriteLine("add");
Console.WriteLine(mf(4, 5));
mf = sub;
Console.WriteLine("sub");
Console.WriteLine(mf(4, 5));
Console.ReadKey();
}
public static int add(int a, int b)
{
return a + b;
}
public static int sub(int a, int b)
{
return (a > b) ? (a - b) : (b - a);
}
}
}
Here, we can see that instead of passing the method name...