0

I understand that callbacks are methods it self , and are passed as an argument to another method.

But why do we need to pass method as an argument while we can directly do that just by calling the method.

For Example:

private static void TakeAction(Action<String> action)
{

}

TakeAction((s) => { Console.WriteLine(s); });

The same can be done just by doing:

private static void TakeAction()
{
    Fo1();
}

private static void Fo1(string s)
{
    Console.WriteLine(s);
}

So why Callback? What specific problem does it address?

samar
  • 5,021
  • 9
  • 47
  • 71
Simsons
  • 12,295
  • 42
  • 153
  • 269

3 Answers3

1

You have a compile time reference to Fo1 method, so you just call it. What if you don't know the method in compile time? How'll you call it? That's why Delegates are useful.

Can you imagine "Linq" without Delegates(or callback as you said). Without delegates linq is nothing. How .Net framework can call your method(defined in your own assembly).?

Well, there is a way. we can use interfaces, but that's no different from java way of doing it. This is c# way of doing it.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

with delegates

By defining a delegate, you are saying to the user of your class "Please feel free to put any method that match this signature here and it will be called each time my delegate is called"

I think thats enough to let u know Why to use call backs when same thing can be done just by calling the method

Community
  • 1
  • 1
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48
  • That's not the point. Just to tell the compiler the signature of method will not wholely the purpose of delegates or callbacks – Simsons Apr 23 '14 at 10:39
0

Delegates (you call them callbacks) are types, which describes what kind of a method they can store in a variable. That gives you an option to choose dynamically which method program uses without a need to use whole Command Pattern (where you have to define a class which implements an interface with a method of your choice).

Mario
  • 241
  • 1
  • 9