I have a library with some methods, and during certain errors I want it to call a method as defined by the caller. This method must return a bool. What I mean is:
Sock sock = new Sock();
sock.OnSpecificError(theMethodToCall);
And then when the error happens, sock should first check to see if OnSpecificError has been set. If it has, it should run it. If the method returns false or if OnSepcificError hasn’t been set, it should throw an exception.
This seems like the sort of thing that delegates are designed for, but for whatever reason I can’t seem to get my mind around what those are actually doing, as in, what is being passed around and how I’d run it later. My current method of handling this is stupid and cumbersome, so any help would be greatly appreciated.
Edit:
Let me clarify a bit. sock.OnSpecificError(method) is used to simply pass sock a method, which it will store, but not run. The idea is then that later one, while sock is running some other methods, if the error pops up, it should run that method. I want to keep the method for use later, and then run it if needed.
The easiest way to start with delegates is by using pre-defined ones. For example, a delegate that takes no arguments and returns a
boolwould beFunc<bool>. A delegate that takes astringand anint, and returns aboolwould beFunc<string,int,bool>, and so on.You define your method like this:
You can now call
OnSpecificErrorlike this:You can also use lambdas to inline small methods, like this: