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
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Define and Use Delegates

The following code example demonstrates how to define and use a delegate. The .NET Framework provides a number of delegates, so often it is not necessary to define new delegates.

The following code example defines a delegate called MyCallback. This new delegate requires that the event handling code (the function that is called as a result of firing the delegate) have a return type of void and takes a String reference.

In the main function, the MyCallback delegate is instantiated using a static method defined by SomeClass. The delegate then becomes an alternate method of calling this function, as demonstrated by sending the string "single" to the delegate object.

Next, additional instances of MyCallback are linked together and then executed with a single call to the delegate object.

// use_delegate.cpp
// compile with: /clr
using namespace System;

ref class SomeClass
   static void Func(String^ str)
      Console::WriteLine("static SomeClass::Func - {0}", str);

ref class OtherClass
   OtherClass( Int32 n ) 
      num = n;

   void Method(String^ str) 
      Console::WriteLine("OtherClass::Method - {0}, num = {1}", 
         str, num);

   Int32 num;

delegate void MyCallback(String^ str);

int main( ) 
   MyCallback^ callback = gcnew MyCallback(SomeClass::Func);   

   callback += gcnew MyCallback(SomeClass::Func);   

   OtherClass^ f = gcnew OtherClass(99);
   callback += gcnew MyCallback(f, &OtherClass::Method);

   f = gcnew OtherClass(100);
   callback += gcnew MyCallback(f, &OtherClass::Method);


   return 0;
static SomeClass::Func - single static SomeClass::Func - chained static SomeClass::Func - chained OtherClass::Method - chained, num = 99 OtherClass::Method - chained, num = 100

Community Additions

© 2015 Microsoft