Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Collapse the table of content
Expand the table of content


Visual Studio .NET 2003

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.

For more information on delegates and their base implementations, see 9 Delegates.


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
#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)));
   return 0;


static handler
static handler

See Also

Managed Extensions for C++ Reference | C++ Keywords

© 2015 Microsoft