C# Delegate Multicasting

Microsoft's .NET framework uses the delegation design pattern extensively. Every time you use an event handler you are using delegation. There are several different ways to implement delegates in .NET, but multicasting is clearly the most flexible way and the one used by Microsoft's classes. In Visual Studio, this happens somewhat automagically through the user interface.

I frequently use delegates with the Unity game engine and wanted to create the shortest possible example using the latest syntactic sugar. The following is what I came up with.

An example of a class that delegates in MyDelegator.cs:

namespace MyNamespace {
    public delegate void MyDelegate();

    public class MyDelegator {
        public MyDelegate MyHandler { get; set; }

        public void DelegateStuff() {
            if (MyHandler != null) {
                MyHandler();
            }
        }
    }
}

And a class that gets delegated to in MyDelegatee.cs:

using System;
using MyNamespace;

namespace MyProgram {
    public class MyDelegatee {
        static void Main() {
            MyDelegator myDelegator = new MyDelegator();

            myDelegator.MyHandler += SomeMethod;
            myDelegator.MyHandler += SomeOtherMethod;
            myDelegator.DelegateStuff();
        }

        public static void SomeMethod() {
            Console.WriteLine("SomeMethod");
        }

        public static void SomeOtherMethod() {
            Console.WriteLine("SomeOtherMethod");
        }
    }
}
Posted on Jan 29, 2013
Written by Emlyn Murphy