Common Type System—Delegates


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Common Type System

© 2006 Wiley Publishing Inc.

Delegates

Delegates are special types in the CTS that represent a strongly typed method signature. Delegate types are derivatives of the special System.Delegate type, which itself derives from System.ValueType. A delegate can be instantiated and formed over any target method and instance combination where the method matches the delegate’s signature. Delegates can be formed over static methods, too, in which case no instance is required. A delegate instance is the CLR’s version of a strongly typed function pointer.

Most languages offer syntax to make delegate creation and instantiation simple. For example, in C# a new delegate type is created using the delegate keyword:

public delegate void MyDelegate(int x, int y);

This says that we create a new delegate type, named MyDelegate, which can be constructed over methods with void return types and that accept two arguments each typed as int. VB has similar syntax. Such syntax hides a lot of the complexity that compiler authors must go through to generate real delegates, making working with delegates straightforward for users of the language.

Our delegate can then be formed over a target, passed around, and then invoked at some point in the future. Invocation in C# looks like any ordinary function call:

class Foo
{
   void PrintPair(int a, int b)
   {
      Console.WriteLine(“a = {0}”, a);
      Console.WriteLine(“b = {0}”, b);
   }
 
   void CreateAndInvoke()
   {
      // Implied ‘new MyDelegate(this.PrintPair)’:
      MyDelegate del = PrintPair;
      del(10, 20);
   }
}

CreateAndInvoke constructs a new MyDelegate, formed over the PrintPair method with the current this pointer as the target, and then invokes it.


Previous_Page_.gif Next_Page_.gif


Personal tools