public abstract class Delegate : ICloneable
Object
DelegateThis type implements ICloneable.
mscorlib
BCL
A class used to create types that invoke methods.
Delegate types derive from the Delegate class. The declaration of a delegate type establishes a contract that specifies the signature of one or more methods. [Note: For an example of a delegate type declaration, see the examples at the end of this topic.]
Delegate types are implicitly sealed: it is not permissible to derive a new type from a delegate type. [Note: The Delegate class is not considered a delegate type; it is a class used to derive delegate types.]
[Note: For information on subclassing the Delegate class, see Partition II of the CLI Specification.]
A delegate is an instance of a delegate type. A non-null delegate references an invocation list, which is made up of one or more entries. Each entry consists of a pair of values: a non-null method, and a corresponding object, called the target. If the method is static, the corresponding target is
null
, otherwise the target is the instance on which the method is to be called.The signature of each method in the invocation list is required to exactly match the signature specified by the delegate's type.
When a delegate is invoked, the methods in the corresponding invocation list are invoked in the order in which they appear in that list. A delegate attempts to invoke every method in its invocation list, with duplicate methods being invoked once for each occurrence in that list.
Delegates are immutable; once created, the invocation list of a delegate does not change. Combining operations, such as System.Delegate.Combine(System.Delegate,System.Delegate) and System.Delegate.Remove(System.Delegate,System.Delegate), cannot alter existing delegates. Instead, such operations result in the return of either a new delegate that contains the results of the operation, an existing delegate, or the null value. [Note: A combining operation returns the null value when the result of the operation is an empty invocation list. A combining operation returns an existing delegate when the requested operation has no effect (for example, if an attempt is made to remove a nonexistent entry).]
If an invoked method throws an exception, the method stops executing and the exception is passed back to the caller of the delegate. The delegate does not continue invoking methods from its invocation list. Catching the exception in the caller does not alter this behavior. It is possible that non-standard methods that implement combining operations allow the creation of delegates with different behavior. When this is the case, the non-standard methods are required to specify the behavior.
When the signature of the methods invoked by a delegate includes a return value, the delegate returns the return value of the last element in the invocation list. When the signature includes a parameter that is passed by reference, the final value of the parameter is the result of every method in the invocation list executing sequentially and updating the parameter's value. [Note: For an example that demonstrates this behavior, see Example 2.]
Example1:
The following example creates two delegates. The first delegate invokes a static method, and the second invokes an instance method on a target object.
using System; public delegate string DelegatedMethod(string s); class MyClass { public static string StaticMethod(string s) { return ("Static method Arg=" + s); } public string InstanceMethod(string s) { return ("Instance method Arg=" + s); } } class TestClass { public static void Main() { MyClass myInstance = new MyClass(); //Create delegates from delegate type DelegatedMethod. DelegatedMethod delStatic = new DelegatedMethod(MyClass.StaticMethod); DelegatedMethod delInstance = new DelegatedMethod(myInstance.InstanceMethod); //Invoke the methods referenced by the delegates. Console.WriteLine (delStatic("Call 1")); Console.WriteLine (delInstance ("Call 2")); } }The output is
Static method Arg=Call 1
Instance method Arg=Call 2
Example2:
The following example shows the return value and the final value of a parameter that is passed by reference to a delegate that invokes multiple methods.
using System; class MyClass { public int Increment(ref int i) { Console.WriteLine("Incrementing {0}",i); return (i++); } public int Negate(ref int i) { Console.WriteLine("Negating {0}",i); i = i * -1; return i; } } public delegate int DelegatedMethod(ref int i); class TestClass { public static void Main() { MyClass myInstance = new MyClass(); DelegatedMethod delIncrementer = new DelegatedMethod(myInstance.Increment); DelegatedMethod delNegater = new DelegatedMethod(myInstance.Negate); DelegatedMethod d = (DelegatedMethod) Delegate.Combine(delIncrementer, delNegater); int i = 1; Console.WriteLine("Invoking delegate using ref value {0}",i); int retvalue = d(ref i); Console.WriteLine("After Invoking delegate i = {0} return value is {1}",i, retvalue); } }The output is
Invoking delegate using ref value 1
Incrementing 1
Negating 2
After Invoking delegate i = -2 return value is -2
System Namespace
Delegate Methods
Delegate.Clone Method
Delegate.Combine(System.Delegate, System.Delegate) Method
Delegate.Combine(System.Delegate[]) Method
Delegate.CreateDelegate(System.Type, System.Object, System.String) Method
Delegate.CreateDelegate(System.Type, System.Type, System.String) Method
Delegate.CreateDelegate(System.Type, System.Reflection.MethodInfo) Method
Delegate.DynamicInvoke Method
Delegate.Equals Method
Delegate.GetHashCode Method
Delegate.GetInvocationList Method
Delegate.Remove Method
Delegate.RemoveAll Method
Delegate.op_Equality Method
Delegate.op_Inequality Method
Delegate Properties
public virtual object Clone();
Creates a copy of the current instance.
A Object that is a copy of the current instance.
The System.Delegate.Clone method creates a new instance of the same type as the current instance and then copies the contents of each of the current instance's non-static fields.[Note: This method is implemented to support the ICloneable interface.]
[Behaviors: The returned object must have the exact same type and invocation list as the current instance.]
[Default: The default implementation of the System.Delegate.Clone method creates a new instance, which is the exact same type as the current instance, and then copies the contents of each of the current instance's non-static fields. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the object referenced by the field is not copied; instead, the returned object contains a copy of the reference. This behavior is identical to System.Object.MemberwiseClone . ]
[Overrides: Subclasses of Delegate should override System.Delegate.Clone to customize the way in which copies of the subclass are constructed. ]
System.Delegate Class, System Namespace
public static Delegate Combine(Delegate a, Delegate b);
Concatenates the invocation lists of the specified delegates.
- a
- The delegate whose invocation list will be first in the invocation list of the new delegate.
- b
- The delegate whose invocation list will be last in the invocation list of the new delegate.
A delegate, ornull
.The following table describes the value returned when a or b is
null
.
When a and b are non-null, this method returns a new delegate with the concatenated invocation lists of a and b .
a b null null null non-null non-null null
Exception Type Condition ArgumentException a and b are not null
and not of the same type.
Unless a or b isnull
, a and b are required to be the exact same type.Consider the following situation, in which D1, D2, D3, D4, and D5 are delegate instances of the same type, D1's invocation list has one entry, E1, and D2's invocation list has one entry, E2.
Then, D3 = Combine(D1, D2) results in D3's having an invocation list of E1 + E2.
Then, D4 = Combine(D2, D1) results in D4's having an invocation list of E2 + E1.
Then, D5 = Combine(D3, D4) results in D5's having an invocation list of E1 + E2 + E2 + E1.
[Note: The invocation list of the returned delegate can contain duplicate methods.
System.Delegate.Combine(System.Delegate,System.Delegate) is useful for creating event handlers that call multiple methods each time an event occurs.
]
System.Delegate Class, System Namespace
public static Delegate Combine(Delegate[] delegates);
Concatenates the invocation lists of the specified delegates.
- delegates
- An array of delegates of the exact same type.
A new delegate, ornull
if delegates isnull
or has onlynull
elements.
Exception Type Condition ArgumentException The non- null
delegates in delegates are not of the same type.
The invocation list of the returned delegate is constructed by concatenating the invocation lists of the delegates in delegates, in increasing subscript order. For example, consider the following situation, in which the elements of delegates have the following invocation lists (where En represents an entry in an invocation list, and null represents an empty invocation list): [0] = E1, [1] = null, [2] = E2 + E3, and [3] = E4 + E5 + E6. When these elements are combined, the resulting delegate contains the invocation list E1 + E2 + E3 + E4 + E5 + E6.Null elements in delegates are not included in the returned delegate.
[Note: The invocation list of the returned delegate can contain duplicate methods.]
System.Delegate Class, System Namespace
public static Delegate CreateDelegate(Type type, object target, string method);
Returns a new delegate with the specified target and instance method as its invocation list.
- type
- The Type of the delegate to return. This Type is required to derive from Delegate .
- target
- An instance of an object that implements method .
- method
- A String containing the name of the instance method to be invoke on target .
A Delegate of type type that invokes method on target.
Exception Type Condition ArgumentNullException type, target, or method is null
.
ArgumentException type does not derive from Delegate. -or-
method is not an instance method.
-or-
target does not implement method.
MethodAccessException The caller does not have the required permission.
[Note: This method is used to dynamically create delegates that invoke instance methods. To create a delegate that invokes static methods, see System.Delegate.CreateDelegate(System.Type,System.Object,System.String)(Type, Type, String).]
Reflection
System.Delegate Class, System Namespace
public static Delegate CreateDelegate(Type type, Type target, string method);
Returns a new delegate with the specified static method as its invocation list.
- type
- The Type of delegate to return. This Type is required to derive from Delegate .
- target
- A Type representing the class that implements method .
- method
- A String containing the name of the static method implemented by target .
A Delegate of type type that invokes method.
Exception Type Condition ArgumentNullException type, target, or method is null
.
ArgumentException type does not derive from Delegate. -or-
method is not a static method.
-or-
target does not implement method .
MethodAccessException The caller does not have the required permission.
[Note: This method is used to dynamically create delegates that invoke static methods. To create a delegate that invokes instance methods, see System.Delegate.CreateDelegate(System.Type,System.Object,System.String)(Type, Object, String).]
Reflection
System.Delegate Class, System Namespace
public static Delegate CreateDelegate(Type type, MethodInfo method);
Returns a new delegate with the specified static method as its invocation list.
- type
- The Type of Delegate to return. This Type is required to derive from Delegate .
- method
- A MethodInfo that reflects a static method.
A Delegate of type type that invokes method.
Exception Type Condition ArgumentNullException type or method is null
.ArgumentException type does not derive from Delegate. -or-
method does not reflect a static method.
InvalidProgramException The Invoke
method of the type delegate was not found.
MethodAccessException The caller does not have the required permission.
[Note: This method is used to dynamically create delegates that invoke static methods. To create a delegate that invokes instance methods, see System.Delegate.CreateDelegate(System.Type,System.Object,System.String)(Type, Object, String).]
Reflection
System.Delegate Class, System Namespace
public object DynamicInvoke(object[] args);
Causes a delegate to invoke the methods in its invocation list using the specified arguments.
- args
- An array of Object instances that are to be passed to the methods in the invocation list of the current instance. Specify
null
if the methods invoked by the current instance do not take arguments.
The Object returned by the last method in the invocation list of the current instance.
Exception Type Condition ArgumentException The type of one or more elements in args is invalid as a parameter to the methods implemented by the current instance.
MethodAccessException The caller does not have the required permissions. -or-
The number, order or type of parameters listed in args is invalid.
TargetException A method in the invocation list of the current instance is an instance method and its target object is null
.-or-
A method in the invocation list of the current instance was invoked on a target object or a class that does not implement it.
System.Reflection.TargetParamterCountException The number of elements in args is not equal to the number of parameters required by the methods invoked by the current instance.
TargetInvocationException A method in the invocation list of the current instance threw an exception.
Reflection
System.Delegate Class, System Namespace
public override bool Equals(object obj);
Determines whether the specified object is equal to the current instance.
- obj
- The Object to compare with the current instance.
true
if obj is equal to the current instance, otherwisefalse
.
Two delegates are equal if they are not null and are of the exact same type, their invocation lists contain the same number of elements, and every element in the invocation list of the first delegate is equal to the element in the corresponding position in the invocation list of the second delegate.Two invocation list elements are equal if they invoke the same instance method on the same target instance, or they invoke the same static method.
[Note: This method overrides System.Object.Equals(System.Object) .]
System.Delegate Class, System Namespace
public override int GetHashCode();
Generates a hash code for the current instance.
A Int32 containing the hash code for this instance.
The algorithm used to generate the hash code is unspecified.[Note: This method overrides System.Object.GetHashCode .]
System.Delegate Class, System Namespace
public virtual Delegate[] GetInvocationList();
Returns the invocation list of the current delegate.
An ordered set of Delegate instances whose invocation lists collectively match those of the current delegate.
[Behaviors: The array contains a set of delegates, each having an invocation list of one entry. Invoking these delegates sequentially, in the order in which they appear in the array, produces the same results as invoking the current delegate. ]
[Overrides: Override System.Delegate.GetInvocationList when subclassing Delegate.]
System.Delegate Class, System Namespace
public static Delegate Remove(Delegate source, Delegate value);
Removes the invocation list of a Delegate from the invocation list of another delegate.
- source
- The delegate from which to remove the invocation list of value.
- value
- The delegate that supplies the invocation list to remove from source.
Returns a new delegate, source, ornull
.If source and value are not
null
, are not equal, and the invocation list of value is contained in the invocation list of source, returns a new delegate with the invocation list of value removed from the invocation list of source.If the invocation lists of source and value are equal, returns
null
.If the invocation list of value is not found in the invocation list of source, returns source.
The following table describes the value returned when source or value is
null
.
source value null null null non-null non-null null
The invocation list of value is required to be an exact match of a contiguous set of elements in the invocation list of source. If the invocation list of value occurs more than once in the invocation list of source, the last occurrence is removed.
The following example demonstrates the System.Delegate.Remove(System.Delegate,System.Delegate) method.
using System; class MyClass { public string InstanceMethod(string s) { return ("Instance String " + s); } } class MyClass2 { public string InstanceMethod2(string s) { return ("Instance String2 " + s); } } public delegate string DelegatedMethod(string s); class TestClass { public static void WriteDelegate (string label, Delegate d) { Console.WriteLine("Invocation list targets for {0}:",label); foreach(Delegate x in d.GetInvocationList()) Console.WriteLine("{0}",x.Target); } public static void Main() { MyClass myInstance = new MyClass(); DelegatedMethod delInstance = new DelegatedMethod(myInstance.InstanceMethod); MyClass2 myInstance2 = new MyClass2(); DelegatedMethod delInstance2 = new DelegatedMethod(myInstance2.InstanceMethod2); DelegatedMethod [] sourceArray = {delInstance, delInstance2, delInstance2, delInstance}; DelegatedMethod [] remove1 = {delInstance}; DelegatedMethod [] remove2 = {delInstance2, delInstance2}; DelegatedMethod [] remove3 = {delInstance2, delInstance}; DelegatedMethod [] remove4 = {delInstance, delInstance2}; DelegatedMethod [] remove5 = {delInstance, delInstance}; Delegate source = Delegate.Combine(sourceArray); // Display invocation list of source TestClass.WriteDelegate("source", source); //Test 1: value occurs in source twice. Delegate value1 = Delegate.Combine(remove1); Delegate result1 = Delegate.Remove(source, value1); TestClass.WriteDelegate("value1", value1); if (result1==null) { Console.WriteLine("removal test 1 result is null"); } else { TestClass.WriteDelegate("result1", result1); } //Test 2: value matches the middle two elements of source. Delegate value2 = Delegate.Combine(remove2); Delegate result2 = Delegate.Remove(source, value2); TestClass.WriteDelegate("value2", value2); if (result2==null) { Console.WriteLine("removal test 2 result2 is null"); } else { TestClass.WriteDelegate("result2", result2); } //Test 3: value matches the last two elements of source. Delegate value3 = Delegate.Combine(remove3); Delegate result3 = Delegate.Remove(source, value3); TestClass.WriteDelegate("value3", value3); if (result3==null) { Console.WriteLine("removal test 3 result3 is null"); } else { TestClass.WriteDelegate("result3", result3); } //Test 4: value matches the first two elements of source. Delegate value4 = Delegate.Combine(remove4); Delegate result4 = Delegate.Remove(source, value4); TestClass.WriteDelegate("value4", value4); if (result4==null) { Console.WriteLine("removal test 4 result4 is null"); } else { TestClass.WriteDelegate("result4", result4); } //Test 5: value does not occur in source. Delegate value5 = Delegate.Combine(remove5); Delegate result5 = Delegate.Remove(source, value5); TestClass.WriteDelegate("value5", value5); if (result5==null) { Console.WriteLine("removal test 5 result5 is null"); } else { TestClass.WriteDelegate("result5", result5); } //Test 6: value exactly matches source. Delegate result6 = Delegate.Remove(source, source); TestClass.WriteDelegate("value=source", source); if (result6==null) { Console.WriteLine("removal test 6 result6 is null"); } else { TestClass.WriteDelegate("result6", result6); } } }The output is
Invocation list targets for source:
MyClass
MyClass2
MyClass2
MyClass
Invocation list targets for value1:
MyClass
Invocation list targets for result1:
MyClass
MyClass2
MyClass2
Invocation list targets for value2:
MyClass2
MyClass2
Invocation list targets for result2:
MyClass
MyClass
Invocation list targets for value3:
MyClass2
MyClass
Invocation list targets for result3:
MyClass
MyClass2
Invocation list targets for value4:
MyClass
MyClass2
Invocation list targets for result4:
MyClass2
MyClass
Invocation list targets for value5:
MyClass
MyClass
Invocation list targets for result5:
MyClass
MyClass2
MyClass2
MyClass
Invocation list targets for value=source:
MyClass
MyClass2
MyClass2
MyClass
removal test 6 result6 is null
System.Delegate Class, System Namespace
public static Delegate RemoveAll(Delegate source, Delegate value);
Removes all matching occurrences of the invocation list of a Delegate from the invocation list of another delegate.
- source
- The delegate from which to remove all matching occurrences of the invocation list of value.
- value
- The delegate that supplies the invocation list to remove from source.
Returns a new delegate, source, ornull
.If source and value are not
null
, are not equal, and the invocation list of value is contained in the invocation list of source, returns a new delegate with all matching occurrences of the invocation list of value removed from the invocation list of source.If the invocation lists of source and value are equal, or if source contains only a succession of invocation lists equal to value, returns
null
.If the invocation list of value is not found in the invocation list of source, returns source.
The following table describes the value returned when source or value is
null
.
source value null null null non-null non-null null
The invocation list of value is required to be an exact match of a contiguous set of elements in the invocation list ofsource. If the invocation list of value occurs more than once in the invocation list of source, all occurrences are removed.
System.Delegate Class, System Namespace
public static bool operator ==(Delegate d1, Delegate d2);
Determines whether the specified delegates are equal.
- d1
- The first delegate to compare.
- d2
- The second delegate to compare.
true
if d1.Equals(d2) returnstrue
; otherwise,false
.
[Note: See System.Delegate.Equals(System.Object).]
System.Delegate Class, System Namespace
public static bool operator !=(Delegate d1, Delegate d2);
Determines whether the specified Delegates are not equal.
- d1
- The first delegate to compare.
- d2
- The second delegate to compare.
true
if d1.Equals(d2) returnsfalse
; otherwise,false
.
[Note: See System.Delegate.Equals(System.Object).]
System.Delegate Class, System Namespace
public MethodInfo Method { get; }
Gets the last method in a delegate's invocation list.
A MethodInfo .
Exception Type Condition MemberAccessException The caller does not have the required permissions.
This property is read-only.
Reflection
System.Delegate Class, System Namespace
public object Target { get; }
Gets the last object upon which a delegate invokes an instance method.
A Object instance, ornull
if the delegate invokes only static methods.
This property is read-only.If the delegate invokes only static methods, this property returns
null
. If the delegate invokes one or more instance methods, this property returns the target of the last instance method/target pair in the invocation list.
Example 1:The following example gets the System.Delegate.Target property values for two delegates. The first delegate invokes a static method, and the second invokes an instance method.
using System; public delegate string DelegatedMethod(string s); class MyClass { public static string StaticMethod(string s) { return ("Static method Arg=" + s); } public string InstanceMethod(string s) { return ("Instance method Arg=" + s); } } class TestClass { public static void Main() { MyClass myInstance = new MyClass(); //Create delegates from delegate type DelegatedMethod. DelegatedMethod delStatic = new DelegatedMethod(MyClass.StaticMethod); DelegatedMethod delInstance = new DelegatedMethod(myInstance.InstanceMethod); object t = delStatic.Target; Console.WriteLine ("Static target is {0}", t==null ? "null":t); t = delInstance.Target; Console.WriteLine ("Instance target is {0}", t==null ? "null":t); } }The output is
Static target is null
Example 2:Instance target is MyClass
The following example gets the System.Delegate.Target property value for three delegates created using instance methods, static methods, and a combination of the two.
using System; class MyClass { public static string StaticMethod(string s) { return ("Static String " + s); } public string InstanceMethod(string s) { return ("Instance String " + s); } } class MyClass2 { public static string StaticMethod2(string s) { return ("Static String2 " + s); } public string InstanceMethod2(string s) { return ("Instance String2 " + s); } } public delegate string DelegatedMethod(string s); class TestClass { public static void Main() { DelegatedMethod delStatic = new DelegatedMethod(MyClass.StaticMethod); DelegatedMethod delStatic2 = new DelegatedMethod(MyClass2.StaticMethod2); MyClass myInstance = new MyClass(); DelegatedMethod delInstance = new DelegatedMethod(myInstance.InstanceMethod); MyClass2 myInstance2 = new MyClass2(); DelegatedMethod delInstance2 = new DelegatedMethod(myInstance2.InstanceMethod2); Delegate d = Delegate.Combine(delStatic, delInstance ); Delegate e = Delegate.Combine(delInstance,delInstance2); Delegate f = Delegate.Combine(delStatic, delStatic2 ); if (d!=null) { Console.WriteLine("Combined 1 static, 1 instance, same class:"); Console.WriteLine("target...{0}", d.Target == null ? "null" : d.Target); foreach(Delegate x in d.GetInvocationList()) Console.WriteLine("invoke element target: {0}",x.Target); } Console.WriteLine(""); if (e!=null) { Console.WriteLine("Combined 2 instance methods, different classes:"); Console.WriteLine("target...{0}", e.Target == null ? "null" : e.Target); foreach(Delegate x in e.GetInvocationList()) Console.WriteLine("invoke element target: {0}",x.Target); } Console.WriteLine(""); if (f!=null) { Console.WriteLine("Combined 2 static methods, different classes:"); Console.WriteLine("target...{0}", f.Target == null ? "null" : f.Target); foreach(Delegate x in f.GetInvocationList()) Console.WriteLine("invoke element target: {0}",x.Target); } } }The output is
Combined 1 static, 1 instance, same class:
target...MyClass
invoke element target:
invoke element target: MyClass
Combined 2 instance methods, different classes:
target...MyClass2
invoke element target: MyClass
invoke element target: MyClass2
Combined 2 static methods, different classes:
target...null
invoke element target:
invoke element target:
System.Delegate Class, System Namespace