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

Returning values from async methods in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the async method skeleton
Write an async method called GetUserNameAsync that returns Task<string> and inside it, return the string "Alice" immediately.
C Sharp (C#)
Need a hint?

Remember to mark the method with async and set the return type to Task<string>.

2
Add delay simulation inside the async method
Inside the GetUserNameAsync method, add a 1 second delay using await Task.Delay(1000); before returning "Alice".
C Sharp (C#)
Need a hint?

Use await Task.Delay(1000); to pause for 1 second before returning the value.

3
Call the async method and store the result
Inside the Main method, call GetUserNameAsync() using await and store the result in a variable called userName.
C Sharp (C#)
Need a hint?

Use string userName = await GetUserNameAsync(); inside Main.

4
Print the returned value
Add a Console.WriteLine statement inside Main to print the value of userName.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(userName); to display the result.