Tarang
Tarang

Reputation: 75955

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?

Upvotes: 0

Views: 3081

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500893

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.

Upvotes: 4

SLaks
SLaks

Reputation: 887479

You're looking for delegates and lambda expressions:

void DoSomething(string whatever, Action<ResultType> callback) {

    callback(...);
}

DoSomething(..., r => ...);

However, you should usually return a Task<T> instead.

Upvotes: 3

Related Questions