CSharp - Use of delegates: call method with and without delegate

Description

Use of delegates: call method with and without delegate

Demo

using System;
delegate int Mydel(int x, int y);

class Program//  w  ww.  j  ava  2s.  c o m
{
    public static int Sum(int a, int b) { return a + b; }

    static void Main(string[] args)
    {
        int a = 25, b = 37;
        //Case-1
        Console.WriteLine("\n Calling Sum(..) method without using a delegate:");
        Console.WriteLine("Sum of a and b is : {0}", Sum(a, b));

        Mydel del = new Mydel(Sum);
        Console.WriteLine("\n Using delegate now:");
        //Case-2
        Console.WriteLine("Calling Sum(..) method with the use of a delegate:");
        //del(a,b) is shorthand for del.Invoke(a,b)
        Console.WriteLine("Sum of a and b is: {0}", del(a, b));
        //Console.WriteLine("Sum of a and b is: {0}", del.Invoke(a, b));
    }
}

Result

Related Topic