Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# delegate dictionary add

Tags:

c#

delegates

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.

like image 493
Xodarap Avatar asked Feb 26 '23 14:02

Xodarap


1 Answers

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).

like image 156
Marc Gravell Avatar answered Mar 07 '23 10:03

Marc Gravell