Delegate




/ Define a delegate

public delegate void MyDelegate(string message);

public class Program

{

    public static void Method1(string message)

    {

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

    }


    public static void Method2(string message)

    {

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

    }


    public static void Main()

    {

        // Step 3: Instantiate the delegate

        MyDelegate del1 = new MyDelegate(Method1);

        MyDelegate del2 = new MyDelegate(Method2);


        // Step 4: Invoke the delegate

        del1("Hello from Method1");

        del2("Hello from Method2");


        // Combining delegates

        MyDelegate delCombined = del1 + del2;

        delCombined("Hello from Combined Delegate");


        // Removing a delegate

        delCombined -= del1;

        delCombined("Hello after removing Method1");

    }

}