MulticastDelegate Simple Sample Examples

Introduction:

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.(Delegates Are Like Function Pointers In C).

Multicast Delegate is a delegate which holds the reference of more than one method.

Note:Delegate Signature And Method Signature Should Be same.

Sample Example 1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace delegateexm
{
    public delegate void mydel(int a,int b);
   public class Program
    {
        public void Sum(int a1,int b1)
        {
            Console.WriteLine(a1 + b1);
        }
        public void Sub(int a2, int b2)
        {
            Console.WriteLine(a2 + b2);
        }
        public void Mul(int a3, int b3)
        {
            Console.WriteLine(a3 * b3);
        }
        static void Main(string[] args)
        {
            Program abc = new Program();
            mydel del1 = new mydel(abc.Sum);
            del1 += abc.Sub;
            del1 += abc.Mul;
            del1(5, 3);
            Console.ReadLine();
        }
    }
}

OutPut:

8
8
15

Sample Example2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace delegateexm
{
    public delegate int mydel(int a,int b);
   public class Program
    {
        public int Sum(int a1,int b1)
        {
            return a1 + b1;
        }
        public int Sub(int a2, int b2)
        {
            return a2 + b2;
        }
        public int Mul(int a3, int b3)
        {
            return a3 + b3;
        }
        static void Main(string[] args)
        {
            Program abc = new Program();
            mydel del1 = new mydel(abc.Sum);
            mydel del2 = new mydel(abc.Sub);
            mydel del3 = new mydel(abc.Mul);
            Console.WriteLine(del1(1, 4));
            Console.WriteLine(del2(4, 3));
            Console.WriteLine(del3(5, 67));
            Console.ReadLine();
        }
    }
}

OutPut:

5
7
72