Callbacks in C# taking the callback directly in the method like in javascript

I have the function in javascript which is something like

dothis(variablea, function(somevalue) {
    ..
});

which comes from function dothis(variablea, callback) {..}

So I want to fire dothis then callback the callback function later, when I get a response from a server.

How would I go about implementing something like this in C#, I've had a look at a couple of examples but I would like to pass the callback function directly into the method. Is this possible?

Jon Skeet
people
quotationmark

Absolutely - you basically want delegates. For example:

public void DoSomething(string input, Action<int> callback)
{
    // Do something with input
    int result = ...;
    callback(result);
}

Then call it with something like this:

DoSomething("foo", result => Console.WriteLine(result));

(There are other ways of creating delegate instances, of course.)

Alternatively, if this is an asynchronous call, you might want to consider using async/await from C# 5. For example:

public async Task<int> DoSomethingAsync(string input)
{
    // Do something with input asynchronously
    using (HttpClient client = new HttpClient())
    {
        await ... /* something to do with input */
    }
    int result = ...;
    return result;
}

The caller can then use that asynchronously too:

public async Task FooAsync()
{
    int result1 = await DoSomethingAsync("something");
    int result2 = await AndSomethingElse(result1);
    Console.WriteLine(result2);
}

If you're basically trying to achieve asynchrony, async/await is a much more convenient approach than callbacks.

people

See more on this question at Stackoverflow