Composable Delegates

April 04, 2022

I’ve been playing around with delegates recently, and came across something that was new to me. Whilst I was familiar with the concept of assigning a delegate; for example:



delegate void delegate1();

private static void UseDelegate()
{
    delegate1 mydelegate;
    mydelegate = func1;

    mydelegate();
}

static void func1() =>
        Console.WriteLine("func1");

I hadn’t realised that it was possible to create a composed delegate, that is, you can simply do the following:



delegate void myDelegate();

private static void ComposableDelegate()
{
    myDelegate del1 = M1;
    myDelegate del2 = M2;
    myDelegate composedDel = del1 + del2;
        
    composedDel();
}

private static void M1() => Console.WriteLine("M1");
private static void M2() => Console.WriteLine("M2");

You can do the exact same thing with Action or Func delegates; for example:



Action action = () => Console.WriteLine("M1");
Action action2 = () => Console.WriteLine("M2");
Action composedDel = action + action2;

composedDel();

References

Combining Delegates



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024