0
0
C Sharp (C#)programming~5 mins

Returning values from async methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Async methods let your program do other work while waiting for a task to finish. Returning values from async methods means you can get results back without stopping everything.

When you want to fetch data from the internet without freezing your app.
When reading a file and you want to keep the app responsive.
When calling a slow database query but still want to do other things.
When you want to perform calculations in the background and get the result later.
Syntax
C Sharp (C#)
async Task<T> MethodNameAsync() {
    // await some async operation
    return result;
}

The method must be marked with async.

The return type is Task<T> where T is the type of value returned.

Examples
This method waits 1 second then returns the number 42.
C Sharp (C#)
async Task<int> GetNumberAsync() {
    await Task.Delay(1000);
    return 42;
}
This method waits half a second then returns a greeting message.
C Sharp (C#)
async Task<string> GetMessageAsync() {
    await Task.Delay(500);
    return "Hello!";
}
Sample Program

This program defines an async method that adds two numbers after a short delay. The Main method waits for the result and then prints it.

C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task<int> CalculateSumAsync(int a, int b) {
        await Task.Delay(500); // Simulate work
        return a + b;
    }

    static async Task Main(string[] args) {
        Console.WriteLine("Starting calculation...");
        int result = await CalculateSumAsync(5, 7);
        Console.WriteLine($"Result is {result}");
    }
}
OutputSuccess
Important Notes

You must use await when calling async methods to get their result.

Async methods returning values use Task<T>, while those not returning values use Task.

Marking a method async allows use of await inside it.

Summary

Async methods can return values using Task<T>.

Use await to get the returned value without blocking.

This helps keep programs responsive during slow operations.