C# and JavaScript – Functions with Implicit Parameters

cfunctionsjavascript

Callback functions are able to accept some parameters, but they are not explicitly declared when calling the function.

How does this actually work? What is going on that allows us to pass a function as a parameter to another function, and implicitly include a parameter in there?

For example:

Javascript

$.get('somefile.php', {func : 'getUserNames'}).done(function(data){
    if(data)
       console.log(data); // '{"0" : "billy", "1" : "bobby"}'
    // This is a js ajax call to a php file. 
    // How exactly am I retrieving "data" ?
}, 'json');

C#

private void BeginReadingData(){
    NetworkStream stream = tcpClient.GetStream();
    stream.BeginRead(buffer, 0, bufferSize, MyCallBack, tcpClient);
}

private void MyCallBack(IAsyncResult ar){
    // Now I can operate on 'ar'
    // why and how? 
}

This is something I understand how to use, just not how to explain or correctly describe the process.

Best Answer

What do you call a callback function that accepts some parameters, but they are not explicitly declared when calling the function?

I'm not sure. In certain cases an object's method may be considered to have the object itself as an implicit parameter.

But there are no function calls with implicit parameters your examples. With a callback, you don't pass the result of calling the function, you pass the function itself.

stream.BeginRead(buffer, 0, bufferSize,
    MyCallBack, /* <- Not a function call, just a reference to a function. */
    tcpClient);

The function that you gave the callback, in these cases $.get and stream.BeginRead will call the callback function you gave them, and explicitly give it the parameters that it should take.

So what you're missing here is the definition of stream.BeginRead has something like:

public virtual ISyncResult BeginRead(
        byte[] buffer,
        int offset,
        int count,
        AsyncCallback callback,
        Object state
    ) {
    /* stuff */

    callback(ar); /* <-- called with explicit parameter */

    /* more stuff */
}
Related Topic