How to Handle Delegate and Multicast Delegates

Delegates

  • A delegate is a method with a parameter and a return type.
  • A delegate is a type that safely encapsulates a method.
  • Delegates are object-oriented, type safe, and secure.

Special Notes

We can’t derive a custom class from the delegates because it is sealed.

[C# Code snippet]

public class MethodClass

{

    public void Method1(string message)

    {

        System.Console.WriteLine("Method1 " + message);

    }

    public void Method2(string message)

    {

        System.Console.WriteLine("Method2 " + message);

    }

}

class Program

{

    public delegate void Del(string message);

    static void Main(string[] args)

    {


        Del handler = DelegateMethod;

        Console.WriteLine("calling a delegate method from current class");

        // Call the delegate.

        handler("Hello World");

        Console.ReadLine();


        MethodClass obj = new MethodClass();

        Del d1 = obj.Method1;

        Del d2 = obj.Method2;

        Del d3 = DelegateMethod;

 


        Del allMethodsDelegate = d1 + d2;

        Console.WriteLine("calling a combined delegate method from other class");

        allMethodsDelegate("Hello World");

        allMethodsDelegate += d3;

        Console.ReadLine();

        Console.WriteLine("calling a combined delegate method from other class and current class");

        allMethodsDelegate("Hello World");

        Console.ReadLine();

        int invocationCount = allMethodsDelegate.GetInvocationList().GetLength(0);

        Console.WriteLine("Getting total count invocation list form a delegate, for the last one " + invocationCount.ToString() + " items (two form other class and one from current class ");

        Console.ReadLine();

    }

 


 

    public static void DelegateMethod(string message)

    {

        Console.WriteLine(message);

    }

 

    public void MethodWithCallback(int param1, int param2, Del callback)

    {

        callback("The number is: " + (param1 + param2).ToString());

    }

}