Reputation: 126
I have a function to do an API call. I want to pass an object through that function to my delegate methods, so that I have flexibility on showing a success/error message.
This object can be a Label, a string, maybe even JSON if I want to go there.
public delegate void ifItWorks(theParameter[] delegateParms,
ref object delegateObject);
public delegate void ifItThrows(theParameter[] delegateParms,
ref object delegateObject);
public static void apiCall(string yourCredentials,
theParameter[] yourParms, ifItWorks sendSuccess, ifItThrows sendAlert,
ref object yourObject)
How do I make this work? I'm fighting the compiler to figure this out.
The usual errors I get are
A ref or out argument must be an assignable
or
Delegate has some invalid arguments
Upvotes: 0
Views: 733
Reputation: 203802
Your API method can just ignore whatever the delegate needs and let the caller of your method use a closure to capture whatever object(s) they need.
public static void apiCall(string yourCredentials, Action sendSuccess, Action sendAlert)
{
try
{
DoSomething();
sendSuccess()
}
catch
{
sendAlert();
}
}
The caller can then write:
var someObject = CreateAnObjectINeed();
apiCall(credentials, () => DoSomething(someObject), () => HandleError(someObject);
Upvotes: 1