Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All


Note   This topic applies only to version 1 of Managed Extensions for C++. This syntax should only be used to maintain version 1 code. See delegate for information on using the equivalent functionality in the new syntax.

Defines a reference type that can be used to encapsulate a method with a specific signature.

__delegate function-declarator

A delegate is roughly equivalent to a C++ function pointer except for the following difference:

  • A delegate can only be bound to one or more methods within a __gc class.

When the compiler encounters the __delegate keyword, a definition of a __gc class is generated. This __gc class has the following characteristics:

  • It inherits from System::MulticastDelegate.

  • It has a constructor that takes two arguments: a pointer to a __gc class or NULL (in the case of binding to a static method) and a fully qualified method of the specified type.

  • It has a method called Invoke, whose signature matches the declared signature of the delegate.

In the following example, a __gc class (MyCalendar) and a delegate (GetDayOfWeek) are declared. The delegate is then bound to the different methods of MyCalendar, invoking each in turn:

// keyword__delegate.cpp
// compile with: /clr:oldSyntax
#using <mscorlib.dll>
using namespace System;

__delegate int GetDayOfWeek();
__gc class MyCalendar {
   MyCalendar() : m_nDayOfWeek(4) {}
   int MyGetDayOfWeek() { 
      Console::WriteLine("handler"); return m_nDayOfWeek; 
   static int MyStaticGetDayOfWeek() { 
      Console::WriteLine("static handler"); 
      return 6;
   int m_nDayOfWeek;

int main () {
   GetDayOfWeek * pGetDayOfWeek;  // declare delegate type
   int nDayOfWeek;
   // bind delegate to static method
   pGetDayOfWeek = new GetDayOfWeek(0, &MyCalendar::MyStaticGetDayOfWeek);
   nDayOfWeek = pGetDayOfWeek->Invoke();

   // bind delegate to instance method
   MyCalendar * pcal = new MyCalendar();
   pGetDayOfWeek = static_cast<GetDayOfWeek*>(Delegate::Combine(pGetDayOfWeek,
      new GetDayOfWeek(pcal, &MyCalendar::MyGetDayOfWeek)));
   nDayOfWeek = pGetDayOfWeek->Invoke();

   // delegate now bound to two methods; remove instance method
   pGetDayOfWeek = static_cast<GetDayOfWeek*>(Delegate::Remove(pGetDayOfWeek,
      new GetDayOfWeek(pcal, &MyCalendar::MyGetDayOfWeek)));

static handler
static handler

Community Additions

© 2015 Microsoft