More on Defining and Using 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.
|

Associating Delegates to Members of a Value Class
The following code sample shows how to associate a delegate with a member of a value class.
// delegate and value class
// compile with: /clr
#include "stdafx.h"
using namespace System;
public delegate void MyDel();
value class ValClas
{
public:
void func1()
{ Console::WriteLine("A test string..."); }
};
int main(array<System::String ^> ^args)
{
ValClas val;
ValClas^ newobj = val;
MyDel^ myfobj = gcnew MyDel(val, &ValClas::func1); // implicit box of val
myfobj();
MyDel^ myfobj2 = gcnew MyDel(newobj, &ValClas::func1);
myfobj2();
return 0;
}
Output:

Associating Delegates to Unmanaged Functions
To associate a delegate with a native function, you must wrap the native function in a managed type, and declare the function to be invoked through PInvoke.
|

Composing Delegates
A useful property of delegate objects is that they can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate. Try the following program example.
// composing delegates
// compile with: /clr
#include "stdafx.h"
using namespace System;
delegate void MyDelegate(String ^ str);
ref class MyClass
{
public:
static void Hello(String ^ str)
{ Console::WriteLine("Hello, {0}!", str); }
static void Goodbye(String ^ str)
{ Console::WriteLine(" Goodbye, {0}!", str); }
};
int main()
{
MyDelegate ^ dela = gcnew MyDelegate(MyClass::Hello);
MyDelegate ^ delb = gcnew MyDelegate(MyClass::Goodbye);
MyDelegate ^ delc = dela + delb;
MyDelegate ^ deld = delc - dela;
Console::Write("Invoking delegate dela: ");
dela("A");
Console::Write("Invoking delegate delb: ");
delb("B");
Console::Write("Invoking delegate delc: ");
delc("C");
Console::Write("Invoking delegate deld: ");
deld("D");
return 0;
}
Output:
