What is the output of this C# code using pattern matching with is and switch?
object obj = 42; string result = obj switch { int i when i > 40 => "Greater than 40", int i => "Integer", string s => "String", _ => "Other" }; Console.WriteLine(result);
Look at the when condition in the switch expression.
The object obj is an integer 42, which matches the first pattern int i when i > 40. Since 42 > 40, it returns "Greater than 40".
Which reason best explains why pattern matching is preferred over multiple if-else statements in C#?
Think about code readability and combining checks.
Pattern matching combines type checks and conditions in a concise way, making code easier to read and maintain compared to many nested if-else statements.
What error does this C# code produce?
object value = "hello"; switch (value) { case string s && s.Length > 3: Console.WriteLine("Long string"); break; default: Console.WriteLine("Other"); break; }
Check the syntax for combining conditions in case patterns.
The code uses '&&' in a case pattern, which is invalid syntax in C#. The correct way is to use a when clause.
What is the output of this C# code using nested pattern matching with tuples?
var point = (X: 0, Y: 5); string quadrant = point switch { (0, 0) => "Origin", (0, var y) when y > 0 => "On positive Y axis", (var x, 0) when x > 0 => "On positive X axis", (var x, var y) when x > 0 && y > 0 => "Quadrant 1", _ => "Other" }; Console.WriteLine(quadrant);
Look at the tuple values and the matching patterns carefully.
The tuple is (0, 5). It matches the pattern (0, var y) with y=5, and since 5 > 0, it returns "On positive Y axis".
Given this method, how many times will the Console.WriteLine print "Matched" when called with the array new object[] { 5, "test", null, 10 }?
void CheckObjects(object[] items) { foreach (var item in items) { if (item is int i && i > 5) Console.WriteLine("Matched"); } } CheckObjects(new object[] { 5, "test", null, 10 });
Count how many integers in the array are greater than 5.
Only the integer 10 is greater than 5, so "Matched" prints once.