CSharp/C# Tutorial - C# Delegates






A delegate is an object to call a method. We can think delegate as function pointer or function type.

A delegate type defines the kind of method that delegate instances can call.

A delegate type defines the method's return type and its parameter types.

Example

The following defines a delegate type called Converter:

delegate int Converter (int x); 

Converter is compatible with any method with an int return type and a single int parameter, such as this:

static int Square (int x) { return x * x; } 

Assigning a method to a delegate variable creates a delegate instance:

Converter t = Square; 

which can be invoked in the same way as a method:

int answer = t(3); // answer is 9 




Example 2

Here's a complete example:

delegate int Converter (int x); 

class Test { 
    static void Main() { 
        Converter t = Square; // Create delegate instance 
        int result = t(3);    // Invoke delegate 
        Console.WriteLine (result); // 9 
    }
    static int Square (int x) { return x * x; } 
} 

A delegate instance acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method.

A delegate is similar to C function pointers.





Multicast Delegates

A delegate instance can reference more than one target methods.

The + and += operators combine delegate instances.

For example:

MyDelegate d = methodB; 
d += methodA; 

Invoking d will now call both methodB and methodA.

Delegates are invoked in the order they are added.

The - and -= operators remove the right delegate operand from the left delegate operand. For example:

d -= methodB; 

Invoking d will now cause only methodA to be invoked.

We can assign a null value to a delegate:

MyDelegate d = null; 
d += methodB; // Equivalent (when d is null) to d = methodB; 

If a multicast delegate has a non-void return type, the caller receives the return value from the last method to be invoked.

The preceding methods are still called, but their return values are discarded.

All delegate types implicitly derive from System.MulticastDelegate, which inherits from System.Delegate.

Instance vs Static Method Targets

When an instance method is assigned to delegate object, the delegate object maintains a reference the method and the instance to which the method belongs.

The System.Delegate class's Target property represents this instance.

For example:

public delegate void Printer (int percentComplete);

class Test {
    static void Main() {
        X x = new X();
        Printer p = x.methodA;
        p(1);
        Console.WriteLine (p.Target == x); // True
        Console.WriteLine (p.Method); // Void methodA(Int32)
    }
}
class X {
    public void methodA (int percentComplete) {
        Console.WriteLine (percentComplete);
    }
}