2

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?

johnny 5
  • 19,893
  • 50
  • 121
  • 195

1 Answers1

1

Pretty self-explanatory:

outputProvider = (Func<int>) Delegate.RemoveAll(outputProvider, valueProvider3);
Charlieface
  • 52,284
  • 6
  • 19
  • 43