C# / .NET Compendium PLEN
.NET / C# / C# — language fundamentals

Callback vs Function - the difference

This question mixes levels a bit - a callback is not a separate technical entity, but a role a function plays in a given context. Every callback IS a function, but not every function is a callback.

A function - the basic unit of code

A function (or a method in C#) is simply a named block of code that you execute directly, when you call it:

int Add(int a, int b) => a + b;

int result = Add(2, 3); // you call IT, you know exactly when it runs - now

You decide when the function runs - you call it and have the result right away (or, with async, you know exactly where in the code its result will appear).

A callback - a function passed as data, called by SOMEONE ELSE

A callback is a function that you pass as a parameter to another function/method, and that other function decides when (or whether at all) to call it. You lose direct control over the moment of execution.

public void ProcessOrder(Order order, Action<Order> onSuccess)
{
    // ... logika przetwarzania
    onSuccess(order); // it is the ProcessOrder method that decides when (and whether) the callback runs,
                       // not the code that called ProcessOrder
}

// The call
ProcessOrder(myOrder, processedOrder =>
{
    Console.WriteLine($"Order {processedOrder.Id} processed!"); // this is the CALLBACK
});

processedOrder => Console.WriteLine(...) is an ordinary function (a lambda) - but in this context it plays the role of a callback, because it is ProcessOrder that decides when to fire it (or not at all, if e.g. it throws an exception earlier).

The key difference in one sentence

Function - you call the code and you control when. Callback - you hand the code to someone else and they control when (and whether) it runs.

This is a difference in control flow (inversion of control), not a technical difference in how the function itself is built.

Examples we have already seen

1. RelayCommand - the _execute passed to the constructor is a callback:

SaveOrderCommand = new RelayCommand(execute: _ => SaveOrder());

You define SaveOrder() (a function), but it is RelayCommand.Execute() that decides when to call it - exactly when WPF determines that the button was clicked. You have no direct control over that.

2. The PropertyChanged event - a handler attached to an event is a callback:

viewModel.PropertyChanged += (sender, e) => Console.WriteLine($"Changed: {e.PropertyName}");

Your code (the lambda) won't run until ViewModelBase.SetProperty calls PropertyChanged?.Invoke(...) - i.e. at a completely different point in time, outside your control.

3. Task.ContinueWith / then in other languages - a classic callback for an asynchronous operation:

_userService.GetUserAsync("123")
    .ContinueWith(task => Console.WriteLine($"Loaded: {task.Result.Name}"));
    // ↑ this callback runs when the task finishes - at an unknown point in the future

4. RetryHelper.ExecuteWithRetryAsync - operation and onRetry are callbacks:

await RetryHelper.ExecuteWithRetryAsync(
    operation: () => _userService.GetUserAsync("123"), // callback - RetryHelper will call it, possibly many times
    onRetry: (ex, attempt) => _logger.LogWarning(...)   // callback - runs ONLY if the operation fails
);

onRetry may run 0, 1 or 2 times, depending on what happens inside ExecuteWithRetryAsync - you don't control that, you only supply "what to do if the need arises".

Synchronous vs asynchronous callback - a distinction they sometimes ask about

A callback doesn't have to be asynchronous - that is a common misconception:

// A synchronous callback - runs IMMEDIATELY, on the same thread, before List.ForEach returns control
orders.ForEach(order => Console.WriteLine(order.Id));

// An asynchronous callback - runs LATER, after the I/O operation completes, possibly on another thread
await File.ReadAllTextAsync(path).ContinueWith(t => Console.WriteLine(t.Result));

In both cases it is a callback (because the method you passed it to controls the call), but they differ in when and on which thread it runs.

An analogy

  • Function = you call someone yourself and wait for the answer on the line - you initiate and control the conversation
  • Callback = you leave someone your phone number ("call me back when you have the results") - you don't know exactly when (or whether at all) they will call back, it is up to them

Summary table

Function (an ordinary call) Callback
Who controls the moment of execution The caller The method the callback was passed to
When it runs Immediately, at the call site At an unknown moment - later, many times, conditionally, or not at all
Example in C# Add(2, 3) An Action/Func passed as a parameter, an event handler
Relation to delegates A delegate can point to a function A callback is a function used in the role of a parameter - technically implemented precisely by a delegate

In short: every callback in C# is implemented as a delegate (because only through a delegate can you "pass a function as a value"), but the word "callback" itself describes the way the function is used (handing it to someone who will decide when to fire it), not its technical construction.

Buy me a coffee