Delegate

What is a delegate?

A delegate is similar to a class that is used for storing the reference to a method and invoking that method at runtime, as required. A delegate can hold the reference of only those methods whose signatures are same as that of the delegate. Some of the examples of delegates are type-safe functions, pointers, or callbacks.



What is a multicast delegate?

Each delegate object holds reference to a single method. However, it is possible for a delegate object to hold references of and invoke multiple methods. Such delegate objects are called multicast delegates.



Example:-


using System;

namespace DelegateDemo
{
    class cal
    {
        private int a, b, c;
        public void set(int a, int b)
        {
            this.a = a;
            this.b = b;
        }
        public void sum()
        {
            c = a + b;
            Console.WriteLine("sum="+c);
        }
        public void sub()
        {
            c = a - b;

            Console.WriteLine("sub=" + c);

        }
    }

    public delegate void Del1(int a, int b);
    public delegate void Del2();


    class Program
    {
        static void Main(string[] args)
        {

            cal obj = new cal();
            //Single Delegate
            Del1 del_obj_1 = new Del1(obj.set);//Register Method reference on Delegate object
            //multicast Delegate 
            Del2 del_obj_2 = new Del2(obj.sub);
            del_obj_2 += new Del2(obj.sum);
            del_obj_1(100, 50); // or del_obj_1.Invoke(100, 50);
            del_obj_2();// or del_obj_2.Invoke();

            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment

Xamarin Android Project App

Xamarin Android Project App 1. Xamarin -- Make a CALCULATOR Android App   https://drive.google.com/open?id=0B8OPCXLrtKPmWC1FWWtFM2lraVk...