Removing All instances of specific delegate from multicast delegates

437 views Asked by At

Note: I'm writing this to have documented answers on my question because I frequently find myself having to manually research this

I'm looking for an efficient deterministic way to remove all instances of a delegate from a multicast delegate. Take tis code for example:

 Func<int> outputProvider = null;

 Func<int> valueProvider1 = () => 1;
 Func<int> valueProvider2 = () => 2;
 Func<int> valueProvider3 = () => 3;
 
 outputProvider += valueProvider1; 
 outputProvider += valueProvider2;
 outputProvider += valueProvider3;
 outputProvider += valueProvider3;
 
 outputProvider -= valueProvider3;

 var value = outputProvider.Invoke();
 Console.WriteLine("Value: " + value);

Even though I removed provider 3 the output is still 3, is there a simple way to remove all instances of a delegate?

1

There are 1 answers

0
Charlieface On BEST ANSWER

Pretty self-explanatory:

outputProvider = (Func<int>) Delegate.RemoveAll(outputProvider, valueProvider3);