c# - What is a callback?

ID : 20041

viewed : 19

Tags : c#callbackc#

Top 5 Answer for c# - What is a callback?

vote vote

91

I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?

vote vote

88

In computer programming, a callback is executable code that is passed as an argument to other code.

Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

vote vote

76

A callback is a function that will be called when a process is done executing a specific task.

The usage of a callback is usually in asynchronous logic.

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.

    public delegate void WorkCompletedCallBack(string result);      public void DoWork(WorkCompletedCallBack callback)     {         callback("Hello world");     }      public void Test()     {         WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter         DoWork(callback);     }      public void TestCallBack(string result)     {         Console.WriteLine(result);     } 

In today C#, this could be done using lambda like:

    public void DoWork(Action<string> callback)     {         callback("Hello world");     }      public void Test()     {         DoWork((result) => Console.WriteLine(result));     } 
vote vote

65

Definition

A callback is executable code that is passed as an argument to other code.

Implementation

// Parent can Read public class Parent {     public string Read(){ /*reads here*/ }; }  // Child need Info public class Child {     private string information;     // declare a Delegate     delegate string GetInfo();     // use an instance of the declared Delegate     public GetInfo GetMeInformation;      public void ObtainInfo()     {         // Child will use the Parent capabilities via the Delegate         information = GetMeInformation();     } } 

Usage

Parent Peter = new Parent(); Child Johny = new Child();  // Tell Johny from where to obtain info Johny.GetMeInformation = Peter.Read;  Johny.ObtainInfo(); // here Johny 'asks' Peter to read 

Links

vote vote

50

A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.

Check out this link.

Top 3 video Explaining c# - What is a callback?

Related QUESTION?