226

What's a callback and how is it implemented in C#?

5
  • Are you referring to ASP.Net callbacks or delegate callback parameters?
    – SLaks
    Jan 26, 2010 at 14:04
  • 9
    It could mean a number of things - in what context have you heard it?
    – UpTheCreek
    Jan 26, 2010 at 14:05
  • 1
    I think he is talking about an Async. Callback Jan 26, 2010 at 14:10
  • 9
    -1 The question is unclear(not enough details).
    – serhio
    Jan 26, 2010 at 14:32
  • if you are looking for AsyncCallBack, look here: stackoverflow.com/questions/1047662/what-is-asynccallback
    – Papak
    Jul 19, 2017 at 14:49

10 Answers 10

1663

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

5
  • 76
    Totally cool explanation. I will use this explanation whenever someone asks, hope I can get rights to use it? Oct 29, 2012 at 20:19
  • 3
    @Nick: lol, go ahead. Noting it for my next intro to code class. Oct 29, 2012 at 20:21
  • 31
    +1: Love it. It ruins the song, but that should read `But here's my number and the instructions for using a specific type of phone (delegate)' May 16, 2013 at 11:09
  • 11
    Note that teaching delegate to other people with that explanation only works with a good choreography :) Jun 12, 2015 at 8:22
  • Found this from a Programmer Humor post lol Mar 2 at 17:44
168

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).

3
  • 14
    actually a callback is a pointer to executable code that is passed as an argument to other code... the page needs a review Sep 13, 2014 at 14:38
  • 8
    @G_G: There is nothing that says it has to be a pointer. It usually is because the data segment is not executable, but that's technically an implementation detail.
    – Joey
    Sep 14, 2014 at 0:33
  • Joey: u are right it's an implementation detail but even the callback is implementation detail. You could rewrite your code without usino a single callback. It's like 'while' vs 'for'. Sep 14, 2014 at 8:14
123

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));
        DoWork(Console.WriteLine); // This also works
    }
0
57

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

2
  • 2
    hi @serhio thank you for your answer. it's still a little murky to me: where exactly is the code passed as an argument to other code Seems to be the adding of the Peter.Read method to the child's delegate?
    – BenKoshy
    Feb 14, 2016 at 20:52
  • 4
    @serhio link's dead.
    – Jude
    Feb 8, 2017 at 6:52
13

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.

2
  • 2
    A callback can be implemented as a delegate to a method, but you could equally say that passing an object that supports a callback method on its interface is a callback.
    – Joe
    Jan 26, 2010 at 14:06
  • Array.Sort(arrayObject); calling obj.CompareTo(anotherObj) on elements of arrayObject is a classic example of callback using Interface (ICompareable) in .Net.
    – Ron5504
    Oct 21, 2015 at 11:26
11

If you referring to ASP.Net callbacks:

In the default model for ASP.NET Web pages, the user interacts with a page and clicks a button or performs some other action that results in a postback. The page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser. However, in some situations, it is useful to run server code from the client without performing a postback. If the client script in the page is maintaining some state information (for example, local variable values), posting the page and getting a new copy of it destroys that state. Additionally, page postbacks introduce processing overhead that can decrease performance and force the user to wait for the page to be processed and re-created.

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx

If you are referring to callbacks in code:

Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.

More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx

7

Dedication to LightStriker:
Sample Code:

class CallBackExample
{
    public delegate void MyNumber();
    public static void CallMeBack()
    {
        Console.WriteLine("He/She is calling you.  Pick your phone!:)");
        Console.Read();
    }
    public static void MetYourCrush(MyNumber number)
    {
        int j;
        Console.WriteLine("is she/he interested 0/1?:");
        var i = Console.ReadLine();
        if (int.TryParse(i, out j))
        {
            var interested = (j == 0) ? false : true;
            if (interested)//event
            {
                //call his/her number
                number();
            }
            else
            {
                Console.WriteLine("Nothing happened! :(");
                Console.Read();
            }
        }
    }
    static void Main(string[] args)
    {
        MyNumber number = Program.CallMeBack;
        Console.WriteLine("You have just met your crush and given your number");
        MetYourCrush(number);
        Console.Read();
        Console.Read();
    }       
}

Code Explanation:

I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.

Please let me know if you have any questions.

2
  • This doesn't adequately answer the question, could you explain what your code is doing, to describe how a callback works, and how it is implemented in C#.
    – Adam
    May 11, 2017 at 0:45
  • Hi Adam, Thanks for your reply. I created the code to implement the funny explanation provided by LightStriker. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method. Please let me know if you have any questions.
    – Mani
    May 11, 2017 at 17:50
3

Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.

2

callback work steps:

1) we have to implement ICallbackEventHandler Interface

2) Register the client script :

 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);

1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)

var finalfield= p1,p2,p3; UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack

2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data //do some server side operation and passed to "callbackResult"

3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side

callbackResult

4) Get the data at client side: ReceiveServerData(text) , in text server response , we wil get.

2

Callback "call me back"

A callback is a function passed as an argument to another function. This technique allows a function to invoke the parameter function argument and even to pass a value back to the caller. A callback function can be designed to run before/after the function has finished and can pass a value.

It is a kind of construct where you call a long running function and ask him to call you back once it has finished with can return a parameter result to the caller.

It's like someone calls you in the middle of your work asking for status and you say "you know what give me 5 min and I will call you back" and at the end you call him to update. If you are a function the caller just added and passed another function that you invoked at the end.

This can simply be written in C# as:

public void TaskForVinod(Action callback){
    //i am still here working..working

    //i have finished, calling you
    callback();
}

//invoke the fuction with a callback
TaskForVinod(() => { 
    Console.Write("Is it finished"); 
});

The one simple example is the iterator function where the return will be multiple times, one can argue that we have yield for it:

public void IterationLoop(int min, int max,Action<int> Callback)
{
    for(int i = min;i<= max;i++)
        Callback(i);
}

//call
IterationLoop(5,50,(x) => { Console.Write(x); }); //will print 5-50 numbers

In the code above the function return type is void but it has an Action<int> callback which is called and sends each item from the loop to the caller.

The same thing can be done with if..else or try..catch block as:

public void TryCatch(Action tryFor,Action catchIt)
{
    try{
        tryFor();
    }
    catch(Exception ex)
    {
        Console.WriteLine($"[{ex.HResult}] {ex.Message}");
        catchIt();
    }
}

And call it as:

TryCatch(()=>{ 
        int r = 44;
        Console.WriteLine("Throwing Exception");
        throw new Exception("something is wrong here");
    }, ()=>{
        Console.WriteLine("It was a mistake, will not try again");
    });

However In 2022 we have Func & Action doing the same, please see the demo code below which shows how this can be be used:

// Define CallbackDemo
public class CallbackDemo
{
    //simple callback
    public void DoWork(Action callback)
    {
        int a = 5;
        int b = 10;
        
        //i will do th maths and call you back
        int result = a + b;
        
        //callback
        callback(); //execute
        Console.WriteLine($"[The Actual Result is {result}]");
    }
    
    //callback with parameter
    public void DoWork(Action<int> callbackWithParameter)
    {
        int a = 5;
        int b = 10;
        
        //i will do th maths and call you back
        int result = a + b;
        
        //callback
        callbackWithParameter(result); //execute
        Console.WriteLine($"[The Actual Result is {result}]");
    }
    
    //callback with return
    public void DoWork(Func<int> callbackWithReturn)
    {
        int a = 5;
        int b = 10;
        
        //i will do the maths and call you back
        int result = a + b;
        
        //callback
        int c = callbackWithReturn(); //execute
        
        result += c;
        Console.WriteLine($"[The Actual Result is {result}]");
    }
    
    //callback with return and parameter
    public void DoWork(Func<int,int> callabckWithParameterAndReturn)
    {
        int a = 5;
        int b = 10;
        
        //i will do th maths and call you back
        int result = a + b;
        
        //callback
        result += callabckWithParameterAndReturn(result); //execute
        Console.WriteLine($"[The Actual Result is {result}]");
    }
}

Finally you can test is as:\

void Main()
{
    var demo = new CallbackDemo();
    demo.DoWork(()=> { Console.WriteLine("I have finished the work"); });
    demo.DoWork((r)=> { Console.WriteLine($"I have finished the work here is the result {r}"); });
    demo.DoWork(()=> { Console.WriteLine($"This is passed with func"); return 5;});
    demo.DoWork((f)=> { Console.WriteLine($"This is passed with func and result is {f}"); return 10;});
    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.