Reputation: 21126
I have a function:
public void Callback()
{
// Does some stuff
}
I want to pass that in to another function, which then passes it to another function, which then executes the function... I have this so far:
public void StartApp() // entry point
{
StartMyAwesomeAsyncPostRequest( Callback );
}
public void StartMyAwesomeAsyncPostRequest( Delegate callback )
{
// Work out some stuff and start a post request
TheActualAsyncPostRequest( callback );
}
public void TheActualAsyncPostRequest( Delegate callback )
{
// Do some jazz then run the delegated function
callback();
}
I have looked through a few other examples but coming from a PHP and javascript background, I'm struggling with the explanations, can you perhaps give me an example or explanation specific to my request? Thanks in advance!
Upvotes: 2
Views: 82
Reputation: 148980
Try declaring the parameter type as a particular kind of delegate. In this case, since your callback doesn't accept any argument and doesn't return any results, use an Action
:
public void StartMyAwesomeAsyncPostRequest(Action callback)
{
TheActualAsyncPostRequest(callback);
}
public void TheActualAsyncPostRequest(Action callback)
{
callback();
}
If you wanted to be able to pass an argument to the callback, use an Action<T>
(or one of its many cousins, to pass more than one argument):
public void StartMyAwesomeAsyncPostRequest(Action<string> callback)
{
TheActualAsyncPostRequest(callback);
}
public void TheActualAsyncPostRequest(Action<string> callback)
{
callback("Foo");
}
Or to get a result from the callback, use a Func<T>
(or one of its many cousins, to pass in any arguments):
public void StartMyAwesomeAsyncPostRequest(Func<string> callback)
{
TheActualAsyncPostRequest(callback);
}
public void TheActualAsyncPostRequest(Func<string> callback)
{
string result = callback();
}
Upvotes: 7