I want to create a method like this:
private static void AddOrAppend<K>(this Dictionary<K, MulticastDelegate> firstList, K key, MulticastDelegate newFunc)
{
    if (!firstList.ContainsKey(key))
    {
        firstList.Add(key, newFunc);
    }
    else
    {
        firstList[key] += newFunc;  // this line fails
    }
}
But this fails because it says you can't add multicast delegates. Is there something I'm missing? I thought the delegate keyword was just shorthand for a class which inherits from MulticastDelegate.
firstList[key] = (MulticastDelegate)Delegate.Combine(firstList[key],newFunc);
with test:
        var data = new Dictionary<int, MulticastDelegate>();
        Action action1 = () => Console.WriteLine("abc");
        Action action2 = () => Console.WriteLine("def");
        data.AddOrAppend(1, action1);
        data.AddOrAppend(1, action2);
        data[1].DynamicInvoke();
(which works)
But tbh, Just use Delegate in place of MulticastDelegate; this is largely a hangover from something that never really worked. Or better; a specific type of delegate (perhaps Action).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With