X hits on this document





308 / 396

Chapter ‎18   Unsafe code

Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types. However, instances of two distinct but structurally equivalent delegate types may compare as equal (§7.9.8).

For example:

delegate int D1(int i, double d);

class A { public static int M1(int a, double b) {...} }

class B { delegate int D2(int c, double d);

public static int M1(int f, double g) {...}

public static void M2(int k, double l) {...}

public static int M3(int g) {...}

public static void M4(int g) {...} }

The delegate types D1 and D2 are both compatible with the methods A.M1 and B.M1, since they have the same return type and parameter list; however, these delegate types are two different types, so they are not interchangeable. The delegate types D1 and D2 are incompatible with the methods B.M2, B.M3, and B.M4, since they have different return types or parameter lists.

The only way to declare a delegate type is via a delegate-declaration. A delegate type is a class type that is derived from System.Delegate. Delegate types are implicitly sealed, so it is not permissible to derive any type from a delegate type. It is also not permissible to derive a non-delegate class type from System.Delegate. Note that System.Delegate is not itself a delegate type; it is a class type from which all delegate types are derived.

C# provides special syntax for delegate instantiation and invocation. Except for instantiation, any operation that can be applied to a class or class instance can also be applied to a delegate class or instance, respectively. In particular, it is possible to access members of the System.Delegate type via the usual member access syntax.

The set of methods encapsulated by a delegate instance is called an invocation list. When a delegate instance is created (§‎15.2) from a single method, it encapsulates that method, and its invocation list contains only one entry. However, when two non-null delegate instances are combined, their invocation lists are concatenated—in the order left operand then right operand—to form a new invocation list, which contains two or more entries.

Delegates are combined using the binary + (§‎7.7.4) and += operators (§‎7.13.2). A delegate can be removed from a combination of delegates, using the binary - (§‎7.7.5) and -= operators (§‎7.13.2). Delegates can be compared for equality (§‎7.9.8).

The following example shows the instantiation of a number of delegates, and their corresponding invocation lists:

delegate void D(int x);

class C { public static void M1(int i) {...}

public static void M2(int i) {...}


Copyright Microsoft Corporation 1999-2003. All Rights Reserved.295

Document info
Document views1158
Page views1158
Page last viewedTue Jan 17 23:51:39 UTC 2017