Delegate Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Updated: June 2010

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.

Inheritance Hierarchy

System.Object
  System.Delegate
    System.MulticastDelegate

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ClassInterfaceAttribute(ClassInterfaceType.AutoDual)> _
<ComVisibleAttribute(True)> _
Public MustInherit Class Delegate
[ClassInterfaceAttribute(ClassInterfaceType.AutoDual)]
[ComVisibleAttribute(true)]
public abstract class Delegate

The Delegate type exposes the following members.

Constructors

  Name Description
Protected method Delegate(Object, String) Initializes a delegate that invokes the specified instance method on the specified class instance.
Protected method Delegate(Type, String) Initializes a delegate that invokes the specified static method from the specified class.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Method Gets the method represented by the delegate.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Target Gets the class instance on which the current delegate invokes the instance method.

Top

Methods

  Name Description
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Combine Concatenates the invocation lists of two delegates.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 CombineImpl Concatenates the invocation lists of the specified delegate and the current delegate.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, MethodInfo) Creates a delegate of the specified type to represent the specified static method.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Object, MethodInfo) Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Object, String) Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, MethodInfo, Boolean) Creates a delegate of the specified type to represent the specified static method, with the specified behavior on failure to bind.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Type, String) Creates a delegate of the specified type that represents the specified static method of the specified class.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Object, MethodInfo, Boolean) Creates a delegate of the specified type that represents the specified static or instance method, with the specified first argument and the specified behavior on failure to bind.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Object, String, Boolean) Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance with the specified case-sensitivity.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Type, String, Boolean) Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Object, String, Boolean, Boolean) Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance, with the specified case-sensitivity and the specified behavior on failure to bind.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 CreateDelegate(Type, Type, String, Boolean, Boolean) Creates a delegate of the specified type that represents the specified static method of the specified class, with the specified case-sensitivity and the specified behavior on failure to bind.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 DynamicInvoke Dynamically invokes (late-bound) the method represented by the current delegate.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals Determines whether the specified object and the current delegate are of the same type and share the same targets, methods, and invocation list. (Overrides Object.Equals(Object).)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

In Silverlight for Windows Phone, this member is overridden by Finalize().

In XNA Framework, this member is overridden by Finalize().
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Returns a hash code for the delegate. (Overrides Object.GetHashCode().)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetInvocationList Returns the invocation list of the delegate.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Remove Removes the last occurrence of the invocation list of a delegate from the invocation list of another delegate.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 RemoveImpl Removes the invocation list of a delegate from the invocation list of another delegate.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Operators

  Name Description
Public operatorStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equality Determines whether the specified delegates are equal.
Public operatorStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Inequality Determines whether the specified delegates are not equal.

Top

Remarks

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

Most languages implement a delegate keyword, and compilers for those languages are able to derive from the MulticastDelegate class; therefore, users should use the delegate keyword provided by the language.

NoteNote:

The common language runtime provides an Invoke method for each delegate type, with the same signature as the delegate. You do not have to call this method explicitly from C# or Visual Basic, because the compilers call it automatically. The Invoke method is useful in reflection when you want to find the signature of the delegate type.

The declaration of a delegate type establishes a contract that specifies the signature of one or more methods. A delegate is an instance of a delegate type that has references to one of the following:

  • An instance method of a type and a target object assignable to that type.

  • An instance method of a type, with the hidden this parameter exposed in the formal parameter list. The delegate is said to be an open instance delegate.

  • A static method.

  • A static method and a target object assignable to the first parameter of the method. The delegate is said to be closed over its first argument.

For examples of delegate binding in these scenarios, see the CreateDelegate(Type, Object, MethodInfo, Boolean) method overload.

When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method. When a delegate represents an open instance method, it stores a reference to the method's entry point. The delegate signature must include the hidden this parameter in its formal parameter list; in this case, the delegate does not have a reference to a target object, and a target object must be supplied when the delegate is invoked.

When a delegate represents a static method, the delegate stores a reference to the method's entry point. When a delegate represents a static method closed over its first argument, the delegate stores a reference to the method's entry point and a reference to a target object assignable to the type of the method's first argument. When the delegate is invoked, the first argument of the static method receives the target object.

The invocation list of a delegate is an ordered set of delegates in which each element of the list invokes exactly one of the methods represented by the delegate. An invocation list can contain duplicate methods. During an invocation, methods are invoked in the order in which they appear in the invocation list. A delegate attempts to invoke every method in its invocation list; duplicates are invoked once for each time they appear in the invocation list. Delegates are immutable; once created, the invocation list of a delegate does not change.

Delegates are referred to as multicast, or combinable, because a delegate can invoke one or more methods and can be used in combining operations.

Combining operations, such as Combine and Remove, do not alter existing delegates. Instead, such an operation returns a new delegate that contains the results of the operation, an unchanged delegate, or nulla null reference (Nothing in Visual Basic). A combining operation returns nulla null reference (Nothing in Visual Basic) when the result of the operation is a delegate that does not reference at least one method. A combining operation returns an unchanged delegate when the requested operation has no effect.

If an invoked method throws an exception, the method stops executing, the exception is passed back to the caller of the delegate, and remaining methods in the invocation list are not invoked. Catching the exception in the caller does not alter this 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.

The closest equivalent of a delegate in C or C++ is a function pointer. A delegate can represent a static method or an instance method. When the delegate represents an instance method, the delegate stores not only a reference to the method's entry point, but also a reference to the class instance. Unlike function pointers, delegates are object-oriented and type safe.

In Silverlight, the BeginInvoke method that is automatically defined on all delegate types always throws a NotSupportedException, so you cannot use it to make asynchronous method calls on thread pool threads. You can use the Dispatcher.BeginInvoke(Delegate, array<Object[]) method overload to execute a method on the thread that a System.Windows.Threading.Dispatcher object is associated with, but this technique uses late binding and does not employ thread pool threads.

Platform Notes

Silverlight for Windows Phone Silverlight for Windows Phone

 A multicast virtual function lookup delegate throws NullReferenceException in Silverlight for Windows Phone, while AccessViolationException is thrown in .

Examples

The following example shows how to define a delegate named myMethodDelegate. Instances of this delegate are created for an instance method and a static method of the nested mySampleClass class. The delegate for the instance method requires an instance of mySampleClass. The mySampleClass instance is saved in a variable named mySC.


Public Class Example

   ' Declares a delegate for a method that takes in an int and returns a String.
   Delegate Function myMethodDelegate(ByVal myInt As Integer) As [String]

   ' Defines some methods to which the delegate can point.
   Public Class mySampleClass

      ' Defines an instance method.
      Public Function myStringMethod(ByVal myInt As Integer) As [String]
         If myInt > 0 Then
            Return "positive"
         End If
         If myInt < 0 Then
            Return "negative"
         End If
         Return "zero"
      End Function 'myStringMethod

      ' Defines a static method.
      Public Shared Function mySignMethod(ByVal myInt As Integer) As [String]
         If myInt > 0 Then
            Return "+"
         End If
         If myInt < 0 Then
            Return "-"
         End If
         Return ""
      End Function 'mySignMethod
   End Class

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      ' Creates one delegate for each method. For the instance method, an
      ' instance (mySC) must be supplied. For the Shared method, the
      ' method name is qualified by the class name.
      Dim mySC As New mySampleClass()
      Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
      Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)

      ' Invokes the delegates.
      outputBlock.Text += String.Format("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5)) & vbCrLf
      outputBlock.Text += String.Format("{0} is {1}; use the sign ""{2}"".", -3, myD1(-3), myD2(-3)) & vbCrLf
      outputBlock.Text += String.Format("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0)) & vbCrLf

   End Sub 'Main

End Class 'SamplesDelegate 


'This code produces the following output:
' 
'5 is positive; use the sign "+".
'-3 is negative; use the sign "-".
'0 is zero; use the sign "".


using System;
public class Example
{

   // Declares a delegate for a method that takes in an int and returns a String.
   public delegate String myMethodDelegate(int myInt);

   // Defines some methods to which the delegate can point.
   public class mySampleClass
   {

      // Defines an instance method.
      public String myStringMethod(int myInt)
      {
         if (myInt > 0)
            return ("positive");
         if (myInt < 0)
            return ("negative");
         return ("zero");
      }

      // Defines a static method.
      public static String mySignMethod(int myInt)
      {
         if (myInt > 0)
            return ("+");
         if (myInt < 0)
            return ("-");
         return ("");
      }
   }

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {

      // Creates one delegate for each method. For the instance method, an
      // instance (mySC) must be supplied. For the static method, use the
      // class name.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate(mySC.myStringMethod);
      myMethodDelegate myD2 = new myMethodDelegate(mySampleClass.mySignMethod);

      // Invokes the delegates.
      outputBlock.Text += String.Format("{0} is {1}; use the sign \"{2}\".", 5, myD1(5), myD2(5)) + "\n";
      outputBlock.Text += String.Format("{0} is {1}; use the sign \"{2}\".", -3, myD1(-3), myD2(-3)) + "\n";
      outputBlock.Text += String.Format("{0} is {1}; use the sign \"{2}\".", 0, myD1(0), myD2(0)) + "\n";
   }

}


/*
This code produces the following output:

5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

Change History

Date

History

Reason

June 2010

Added information about the Invoke method.

Customer feedback.