Skip to content

Invoking a Delegate

The important things to know about invoking a delegate are the following:

  • You can invoke a delegate in either of two ways. First, you can call the delegate as if it
    were simply a method. Second, you can use the Invoke method on the delegate.
  • Place the parameters within the parentheses of the call, as shown in the next code
    block. The parameters used to invoke the delegate are used to invoke each of the
    methods on the invocation list (unless one of the parameters is an output parameter,
    which we’ll cover shortly).
  • If a method is in the invocation list more than once, then when the delegate is
    invoked, the method will be called each time it is encountered in the list.
  • The delegate must not be empty (null) when invoked, or it will throw an exception.
    You can use an if statement to check, or you can use the null conditional operator
    and the Invoke method.

 

The following code shows an example of creating and using the delVar delegate, which takes a single integer input value. Invoking the delegate with a parameter causes it to invoke each of the members in its invocation list with the same parameter value. The code shows both ways of invoking the delegate—calling as method and using Invoke. Below figure illustrates the invocation.

When the delegate is invoked, it executes each of the methods in its invocation list, with the same parameters with which it was called.

Delegate Example

The following code defines and uses a delegate with no parameters and no return value. Note the following
about the code:
• Class Test defines two print functions.
• Method Main creates an instance of the delegate and then adds three more methods.
• The program then invokes the delegate, which calls its methods. Before invoking the delegate, however, it checks to make sure it’s not null.

				
					// Define a delegate type with no return value and no parameters.
delegate void PrintFunction();
class Test
{
    public void Print1()
    { 
    Console.WriteLine("Print1 -- instance"); 
    }

    public static void Print2()
    { 
    Console.WriteLine("Print2 -- static"); 
    }
}


class Program
{
    static void Main()
    {
        Test t = new Test(); // Create a test class instance.
        PrintFunction pf; // Create a null delegate.
        pf = t.Print1; // Instantiate and initialize the delegate.
        // Add three more methods to the delegate.
        pf += Test.Print2;
        pf += t.Print1;
        pf += Test.Print2;
        // The delegate now contains four methods.
        if( null != pf ) // Make sure the delegate isn't null.
        pf(); // Invoke the delegate.
        else
        Console.WriteLine("Delegate is empty");
    }
}

//This code produces the following output:

Print1 -- instance
Print2 -- static
Print1 -- instance
Print2 -- static
				
			

Leave a Reply

Your email address will not be published.