delegate in c# with example

Multicast Delegate Example in C#.Net

What are Multicast delegate, type and use?

The multicast delegate is hold the references of more than one methods within the delegate object using the (+=) operator.
1.      Delegate is added using the (+=) operator. 
2.      Delegate is removed using the (-=) operator. 

Example for Multicast Delegate as following,

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

namespace MulticastDelegateExample
{
    public delegate int MulticastDelegateName(int num1, int num2);

    public class MulticastClass
    {

        public static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
        public static int Sub(int num1, int num2)
        {
            return num1 - num2;
        }
        static void Main(string[] args)
        {
            //Create the Add Delegate Instance
            MulticastDelegateName objDelegt = new MulticastDelegateName(Add);
            
            Console.WriteLine("Please enter numbers!");

            int num1 = Int32.Parse(Console.ReadLine());
            int num2 = Int32.Parse(Console.ReadLine());

            int AddRest = objDelegt(num1, num2);
            Console.WriteLine("Result :" + AddRest);

            //Create the Sub Delegate Instance
            objDelegt += new MulticastDelegateName(Sub);
            int subRest = objDelegt(num1, num2);
            Console.WriteLine("Result :" + subRest);

            Console.ReadLine();
        }
    }
}

The Output as given below,

Please enter numbers!
num1 = 20
num2 = 10

Results: Add: 30 and Sub: 10
===============================



ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^