The concept of delegates aren't too new to me but I cannot seem to find out how to get all results from a Func delegates. More specifically, I have a class that has a Func delegate that returns a type bool. Something like this...
private Func<Employee, Shift, bool> qualificationCheckCallback;
There are both 'register' and 'unregister' methods for the callback as well. My goal is to see if any of the methods stored in the delegate return false when invoked later in code. Any insight you may have on this issue is much appreciated! Thanks.
As mentioned in Andrew's answer, if you simply invoke
qualificationCheckCallback
like a normal method, you'll only get back the return value from one of the methods. For this reason, it's pretty unusual to have multicast delegates that have a return value.If your goal is to see if at least one of the methods stored in your delegate returns false, you'll need to invoke the methods individually. Here is one way to do that using the Delegate.GetInvocationList() method:
I'm not suggesting this is a good practice, but it can be done.
A quick search on MSDN found this thread:
https://social.msdn.microsoft.com/Forums/en-US/38a638fe-4a7d-44d6-876c-729d90c20737/how-to-get-return-value-from-delegate?forum=csharplanguage
You are using the wrong pattern. I'd recommend storing a list of these delegates and iterating over the list, rather than using multidelegates to call multiple targets.
You can make this work (if you need to) by changing the signature to include a "state" variable that is passed by reference to each caller:
Keep in mind, this requires the callees to honor the signature, and not overwrite anyone else's failed state:
Of course, you can also extend this pattern to make it safer: