Export (0) Print
Expand All

Delegate Class

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.

For a list of all members of this type, see Delegate Members.

System.Object
   System.Delegate
      System.MulticastDelegate

[Visual Basic]
<Serializable>
<ClassInterface(ClassInterfaceType.AutoDual)>
MustInherit Public Class Delegate
   Implements ICloneable, ISerializable
[C#]
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
public abstract class Delegate : ICloneable, ISerializable
[C++]
[Serializable]
[ClassInterface(ClassInterfaceType::AutoDual)]
public __gc __abstract class Delegate : public ICloneable,
   ISerializable
[JScript]
public
   Serializable
 ClassInterface(ClassInterfaceType.AutoDual)
abstract class Delegate implements ICloneable,
   ISerializable

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.

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.

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, and references one or more of the following:

  • A target object that is not a null reference (Nothing in Visual Basic) and an instance method of the target object
  • A static method

A delegate can reference a method only if the signature of the method exactly matches the signature specified by the delegate type. When a delegate references an instance method, the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is the class instance that the method is invoked on. The target of an instance method cannot be a null reference (Nothing). When a delegate references a static method, the delegate stores a reference to the method's entry point. The target of a static method is a null reference (Nothing).

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 invoked by the delegate. An invocation list can contain duplicate methods. During an invocation, a delegate invokes methods 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.

A delegate is either multicast (combinable) or singlecast (noncombinable). Multicast or combinable delegates invoke one or more methods, and can be used in combining operations. Singlecast or noncombinable delegates invoke exactly one method and cannot be used in combining operations. The invocation list of a singlecast delegate A contains a single element: a reference to A.

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 a null reference (Nothing). A combining operation returns a null reference (Nothing) 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.

Compilers provide two additional methods to the delegate: BeginInvoke and EndInvoke. For more information on these methods, see Asynchronous Programming Overview.

The closest equivalent of a delegate in C or C++ is a function pointer. However, a function pointer can only reference static functions, whereas a delegate can reference both static and instance methods. When the delegate references an instance method, the delegate stores not only a reference to the method's entry point, but also a reference to the class instance for which to invoke the method. Unlike function pointers, delegates are object-oriented and type-safe.

Example

[Visual Basic, C#, C++] The following example shows how to define a standard delegate.

[Visual Basic] 
Imports System

Public Class SamplesDelegate

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

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

      ' Defines an instance method.
      Public Function myStringMethod(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(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 'mySampleClass

   Public Shared Sub Main()

      ' Creates one delegate for each method.
      Dim mySC As New mySampleClass()
      Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
      Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)

      ' Invokes the delegates.
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", - 3, myD1(- 3), myD2(- 3))
      Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0))

   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 "".



[C#] 
using System;
public class SamplesDelegate  {

   // 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 Main()  {

      // Creates one delegate for each method.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );

      // Invokes the delegates.
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", -3, myD1( -3 ), myD2( -3 ) );
      Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
   }

}


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


[C++] 
#using <mscorlib.dll>

using namespace System;

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

// Defines some methods to which the delegate can point.
__gc class mySampleClass {
public:
   // Defines an instance method.
   String* myStringMethod (int myInt) {
      if (myInt > 0)
         return(S"positive");
      if (myInt < 0)
         return(S"negative");
      return (S"zero");
   }

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

int main() {

   // Creates one delegate for each method.
   mySampleClass* mySC = new mySampleClass();
   myMethodDelegate* myD1 = new myMethodDelegate(mySC, mySampleClass::myStringMethod);
   myMethodDelegate* myD2 = new myMethodDelegate(0, mySampleClass::mySignMethod);

   // Invokes the delegates.
   Console::WriteLine(S"{0} is {1}; use the sign \"{2}\".", __box(5), myD1(5), myD2(5));
   Console::WriteLine(S"{0} is {1}; use the sign \"{2}\".", __box(-3), myD1(-3), myD2(-3));
   Console::WriteLine(S"{0} is {1}; use the sign \"{2}\".", __box(0), myD1(0), myD2(0));
}

/*
This code produces the following output:

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

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

Delegate Members | System Namespace | MulticastDelegate | Asynchronous Programming Overview

Show:
© 2014 Microsoft