Posted by : Sudhir Chekuri Saturday, 9 January 2016

  • Delegate is a type which can hold reference of multiple methods.
  • All the methods should have same signature of the delegate.
  • It contains return type.
  • The i/o parameters of the delegate should be exactly same as i/o parameters of the method.
  • Semicolon is required at the end of delegate.
Syntax

public delegate void/type delegatename(parameters);

Delegates are of 2 types.

1. Singlecast delegate

2. Multicast delegate

Singlecast Delegate

If a delegate is used for invoking a single method it is called as "Singlecast delegates".

Example for Singlecast delegate
using System;

namespace delegates
{
    class Program
    {
        static void Main(string[] args)
        {
            del d = new del(Program.add);
            int i = d(12, 44);
            Console.WriteLine(i);
            Console.ReadKey();
        }
        public static int add(int c, int d)
        {
            return c + d;
        }
    }
    public delegate int del(int a, int b);
}



Output

56

Multicast Delegate

If a delegate is used for calling more than one method it is called as "Multicast delegates". In multicasting delegates method should have only void type. It can hold reference of multiple methods.

Example for multicast delegate

Program
using System;

namespace delegates
{
    class delegat
    {
        static void Main(string[] args)
        {
            del d = new del(delegat.add);
            d = d + delegat.sub;
            d = d + delegat.mul;
            d = d + delegat.div;
            d(12, 44);
            Console.ReadKey();
        }
        public static void add(int c, int d)
        {
            Console.WriteLine(c + d);
        }
        public static void sub(int c, int d)
        {
            Console.WriteLine(c - d);
        }
        public static void mul(int c, int d)
        {
            Console.WriteLine(c * d);
        }
        public static void div(int c, int d)
        {
            Console.WriteLine(c / d);
        }
    }
    public delegate void del(int a, int b);
}

Output

56

-32

528

0

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -