Sunday 29 May 2016

Understanding Delegate in C#


  1. Delegates is method pointer in c#.It encapsulate method safely.
  2. Method must have same signature as delegate.
  3. Delegates are object-oriented , type safe and secure.
  4. Delegate type derived from Delegate Class in .net.
  5. Method can be passed as parameter in delegate.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Delegates
{

    class Program
    {
        public delegate int MyDel(int a, int b);

        static void Main(string[] args)
        {
            Example ex = new Example();
            MyDel sum = new MyDel(ex.Sum);
            MyDel dif = new MyDel(ex.Difference);
            Console.WriteLine(sum(3, 5));
            Console.WriteLine(dif(45, 77));
            Console.ReadKey();
        }
    }

    public class Example
    {
        //same signature as delegate
        public int Sum(int a, int b)
        {
            return a + b;
        }
        //same signature as delegate
        public int Difference(int a, int b)
        {
            return a - b;
        }
    }
}