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

Deferred execution behavior in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Deferred Execution Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of deferred execution with LINQ query
What is the output of this C# code snippet that uses deferred execution in LINQ?
C Sharp (C#)
List<int> numbers = new() {1, 2, 3};
var query = numbers.Select(x => x * 2);
numbers.Add(4);
foreach (var num in query)
{
    Console.Write(num + " ");
}
A2 4 6 8
B2 4 6
C1 2 3 4
DRuntime error
Attempts:
2 left
💡 Hint
Remember that LINQ queries are not executed until you enumerate them.
Predict Output
intermediate
2:00remaining
Effect of modifying source collection after query creation
What will be printed by this C# program?
C Sharp (C#)
var list = new List<string> {"a", "b", "c"};
var filtered = list.Where(s => s != "b");
list.Remove("a");
foreach (var item in filtered)
{
    Console.Write(item);
}
Abc
Bc
Cab
DRuntime exception
Attempts:
2 left
💡 Hint
Consider when the Where filter is applied and the current state of the list.
🔧 Debug
advanced
2:00remaining
Why does this deferred execution code print unexpected results?
Consider this code snippet: List nums = new() {1, 2, 3}; var query = nums.Select(x => x + 1); nums = new List {4, 5, 6}; foreach (var n in query) { Console.Write(n + " "); } Why does the output not reflect the new list values?
C Sharp (C#)
List<int> nums = new() {1, 2, 3};
var query = nums.Select(x => x + 1);
nums = new List<int> {4, 5, 6};
foreach (var n in query)
{
    Console.Write(n + " ");
}
ANo output
B5 6 7
CRuntime error
D2 3 4
Attempts:
2 left
💡 Hint
Think about what the query captures and what the variable reassignment does.
📝 Syntax
advanced
2:00remaining
Which LINQ query causes a runtime error due to deferred execution?
Given the following code, which option will cause an exception when enumerated?
C Sharp (C#)
List<int> numbers = new() {1, 2, 3};
var query = numbers.Select(x => 10 / x);
foreach (var val in query)
{
    Console.Write(val + " ");
}
Avar query = numbers.Select(x => 10 / (x - 1));
Bvar query = numbers.Select(x => 10 / x);
Cvar query = numbers.Select(x => 10 / (x + 1));
Dvar query = numbers.Select(x => 10 / (x - 2));
Attempts:
2 left
💡 Hint
Check for division by zero possibilities during enumeration.
🚀 Application
expert
3:00remaining
Predict the final count after deferred execution with side effects
What is the value of count printed by this C# program?
C Sharp (C#)
List<int> data = new() {1, 2, 3, 4};
int count = 0;
var query = data.Where(x => { count++; return x % 2 == 0; });

// No enumeration here
count += 10;

foreach (var item in query)
{
    // Just iterate
}

Console.Write(count);
A10
B12
C14
DRuntime error
Attempts:
2 left
💡 Hint
Remember when the lambda inside Where is executed and how many elements it processes.