Returning values from async methods
📖 Scenario: You are building a simple program that fetches user data asynchronously, simulating a real-world scenario where data comes from a slow source like a web server.
🎯 Goal: Create an async method that returns a value, then call it and display the result.
📋 What You'll Learn
Create an async method called
GetUserNameAsync that returns a Task<string>.Inside
GetUserNameAsync, simulate a delay of 1 second using await Task.Delay(1000).Return the string
"Alice" from GetUserNameAsync.Call
GetUserNameAsync from Main using await and store the result in a variable called userName.Print the value of
userName to the console.💡 Why This Matters
🌍 Real World
Async methods that return values are common when fetching data from web APIs, databases, or files without freezing the app.
💼 Career
Understanding async methods and how to get their results is essential for writing responsive and efficient C# applications.
Progress0 / 4 steps