async Task<int> GetNumberAsync() { return 5; }
async Task Main()
{
int result = await GetNumberAsync();
Console.WriteLine(result);
}
medium
A. Task<int>
B. 5
C. Compilation error
D. 0
Solution
Step 1: Understand async method return and await
The method GetNumberAsync returns a Task<int> with value 5. Await unwraps the value.
Step 2: Check what is printed
The awaited result is 5, so Console.WriteLine(result) prints 5.
Final Answer:
5 -> Option B
Quick Check:
Await unwraps Task<int> to int value 5 [OK]
Hint: Await unwraps Task<T> to get the value [OK]
Common Mistakes:
Printing Task<int> instead of awaited int
Expecting compilation error due to async
Assuming default int value 0 is printed
4. Identify the error in this async method:
async Task<int> CalculateAsync()
{
int value = 10;
return Task.FromResult(value);
}
medium
A. No error, code is correct
B. Method should return int, not Task<int>
C. Missing await keyword before Task.FromResult
D. Returning Task.FromResult inside async method causes nested Task
Solution
Step 1: Analyze return statement in async method
Async methods can return Task<T> directly, such as Task.FromResult(value), which is a common and valid pattern for completed tasks.
Step 2: Verify the code runs correctly
The async state machine properly handles the returned Task<int>, producing a single Task<int> with value 10 for the caller. No nesting or errors occur.
Final Answer:
No error, code is correct -> Option A
Quick Check:
Task.FromResult is valid in async Task<int> methods [OK]
Hint: Task.FromResult(value) is valid in async Task<T> methods [OK]
Common Mistakes:
Misunderstanding that Task.FromResult causes nested Tasks
Thinking async methods must return T directly, not Task<T>
Believing await is required before Task.FromResult
5. You want to write an async method that fetches user data and returns the user's name as a string. The fetching is simulated by a delay. Which of the following implementations correctly returns the name without blocking the caller?
hard
A. async string GetUserNameAsync() { await Task.Delay(1000); return \"Alice\"; }
B. Task<string> GetUserNameAsync() { return \"Alice\"; }
C. async Task<string> GetUserNameAsync() { await Task.Delay(1000); return \"Alice\"; }
D. async Task GetUserNameAsync() { await Task.Delay(1000); return \"Alice\"; }"
Solution
Step 1: Check method signature and return type
The method must be async and return Task<string> to return a string asynchronously.
Step 2: Verify method body and return statement
async Task<string> GetUserNameAsync() { await Task.Delay(1000); return \"Alice\"; } uses await Task.Delay(1000) to simulate delay and returns the string correctly. Others have wrong return types or missing async.