I am trying to understand "callback pattern". Every answer says that this is done with delegates (which I know them). But the codes on the answers are something like that:
public delegate void Callback(string result);
public void Test()
{
CallBack callback = CallbackFunction;
DoWork(callback);
}
public void DoWork(CallBack callback)
{
callback("Hello world");
}
public void CallbackFunction(string result)
{
Console.WriteLine(result);
}
I really don't understand, why we need delegate for this? We can do this in this way too?
public void Test()
{
DoWork();
}
public void DoWork()
{
CallbackFunction("Hello world");
}
public void CallbackFunction(string result)
{
Console.WriteLine(result);
}
Besides that, for example in Java, a callback means a real "return" to the main program's "particular function" after an event. But when we use delegates, isn't this just calling another method?
How can we make a callback that finally calls an OnFail()
method on fail, and OnSuccess()
method on success. I am really confused. Can somebody help me to understand this?