tags:

views:

59

answers:

1

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.

+8  A: 
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).

Marc Gravell
Thanks! This answers my question, but do you know why my code didn't work?
Xodarap