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

Task and Task of T types in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Task Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple Task returning a string
What is the output of this C# program when run?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        Task<string> task = Task.FromResult("Hello World");
        string result = await task;
        Console.WriteLine(result);
    }
}
AHello World
BTask`1
CSystem.Threading.Tasks.Task
DCompilation error
Attempts:
2 left
💡 Hint
Remember that Task.FromResult creates a completed Task with the given result.
Predict Output
intermediate
2:00remaining
Value of Task after delay
What will be the output of this program?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        Task<int> task = GetNumberAsync();
        int value = await task;
        Console.WriteLine(value);
    }

    static async Task<int> GetNumberAsync() {
        await Task.Delay(100);
        return 42;
    }
}
ATask`1
B0
C42
DRuntime exception
Attempts:
2 left
💡 Hint
The method returns 42 after a short delay.
Predict Output
advanced
2:00remaining
What happens when awaiting a non-generic Task?
Consider this code snippet. What is printed when it runs?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        Task task = Task.Delay(50);
        await task;
        Console.WriteLine("Done");
    }
}
ADone
BTask
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Awaiting a Task waits for its completion but returns no value.
🧠 Conceptual
advanced
2:00remaining
Difference between Task and Task
Which statement correctly describes the difference between Task and Task in C#?
ATask<T> is used only for synchronous operations, Task only for asynchronous.
BTask represents an operation that returns no value, while Task<T> represents an operation that returns a value of type T.
CTask<T> can only be awaited, Task cannot be awaited.
DTask and Task<T> are identical and interchangeable.
Attempts:
2 left
💡 Hint
Think about whether the operation returns a result or not.
🔧 Debug
expert
2:00remaining
Identify the runtime error in this Task usage
What error will this code produce when run?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program {
    static void Main() {
        Task<int> task = Task.Run(() => 10 / 0);
        Console.WriteLine(task.Result);
    }
}
ANo error, prints 0
BSystem.DivideByZeroException
CCompilation error
DSystem.AggregateException
Attempts:
2 left
💡 Hint
Exceptions inside Tasks are wrapped when accessing Result.