We recommend using Visual Studio 2017
This documentation is archived and is not being maintained.

How to: Compose Delegates

This topic demonstrates how to compose 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.


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

delegate void MyDelegate(String ^ s);

ref class MyClass {
   static void Hello(String ^ s) {
      Console::WriteLine("Hello, {0}!", s);

   static void Goodbye(String ^ s) {
      Console::WriteLine("  Goodbye, {0}!", s);

int main() {

   MyDelegate ^ a = gcnew MyDelegate(MyClass::Hello);
   MyDelegate ^ b = gcnew MyDelegate(MyClass::Goodbye);
   MyDelegate ^ c = a + b;
   MyDelegate ^ d = c - a;

   Console::WriteLine("Invoking delegate a:");
   Console::WriteLine("Invoking delegate b:");
   Console::WriteLine("Invoking delegate c:");
   Console::WriteLine("Invoking delegate d:");


Invoking delegate a:
Hello, A!
Invoking delegate b:
  Goodbye, B!
Invoking delegate c:
Hello, C!
  Goodbye, C!
Invoking delegate d:
  Goodbye, D!