Challenge - 5 Problems
Type Patterns Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of type pattern matching with 'is' and 'not'
What is the output of this C# code snippet?
C Sharp (C#)
object obj = 42; if (obj is not string s) { Console.WriteLine("Not a string"); } else { Console.WriteLine($"String: {s}"); }
Attempts:
2 left
💡 Hint
Remember that 'is not' checks if the object is NOT of the specified type.
✗ Incorrect
The variable 'obj' holds an int (42), which is not a string. The pattern 'obj is not string s' evaluates to true, so the first branch runs, printing 'Not a string'.
❓ Predict Output
intermediate2:00remaining
Output of switch expression with type patterns
What will this C# switch expression output?
C Sharp (C#)
object val = 3.14; string result = val switch { int i => $"Integer {i}", double d => $"Double {d}", _ => "Unknown" }; Console.WriteLine(result);
Attempts:
2 left
💡 Hint
Check the runtime type of 'val' and which pattern matches first.
✗ Incorrect
The variable 'val' holds a double 3.14, so the pattern 'double d' matches and returns 'Double 3.14'.
🔧 Debug
advanced2:00remaining
Identify the error in type pattern usage
This code snippet causes a compilation error. What is the cause?
C Sharp (C#)
object obj = "hello"; if (obj is int i && i > 0) { Console.WriteLine(i); }
Attempts:
2 left
💡 Hint
Try compiling and running the code to see if it works.
✗ Incorrect
The code compiles fine. The pattern 'obj is int i' checks if obj is int and assigns to i. The '&& i > 0' is a valid condition. Since obj is a string, the if block does not run, but no error occurs.
❓ Predict Output
advanced2:00remaining
Output of nested type patterns with property patterns
What is the output of this C# code?
C Sharp (C#)
record Point(int X, int Y); object obj = new Point(3, 4); string output = obj switch { Point { X: 3, Y: 4 } p => $"Point at (3,4)", Point p => $"Point at ({p.X},{p.Y})", _ => "Unknown" }; Console.WriteLine(output);
Attempts:
2 left
💡 Hint
Look at the property pattern matching inside the switch.
✗ Incorrect
The object is a Point with X=3 and Y=4, so the first pattern matches exactly and returns 'Point at (3,4)'.
❓ Predict Output
expert2:00remaining
Output of complex pattern matching with 'or' and 'and' patterns
What is the output of this C# code snippet?
C Sharp (C#)
object val = 10; string result = val switch { int i and (> 0 and < 5) => "Between 1 and 4", int i and (>= 5 or < 0) => "Outside 1 to 4", _ => "Other" }; Console.WriteLine(result);
Attempts:
2 left
💡 Hint
Check how the 'and' and 'or' patterns combine conditions.
✗ Incorrect
The value 10 is an int and matches the second pattern: int i and (>= 5 or < 0). Since 10 >= 5, it returns 'Outside 1 to 4'.