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

Type patterns in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Patterns Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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}");
}
ANot a string
BString: 42
CCompilation error
DNo output
Attempts:
2 left
💡 Hint
Remember that 'is not' checks if the object is NOT of the specified type.
Predict Output
intermediate
2: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);
AInteger 3
BUnknown
CDouble 3.14
DCompilation error
Attempts:
2 left
💡 Hint
Check the runtime type of 'val' and which pattern matches first.
🔧 Debug
advanced
2: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);
}
ANo error, code compiles fine
BThe variable 'i' is not declared before use
CThe 'is' pattern cannot be combined with '&&' operator
DCannot use relational operator '>' on 'int' in pattern matching
Attempts:
2 left
💡 Hint
Try compiling and running the code to see if it works.
Predict Output
advanced
2: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);
ACompilation error
BPoint at (0,0)
CUnknown
DPoint at (3,4)
Attempts:
2 left
💡 Hint
Look at the property pattern matching inside the switch.
Predict Output
expert
2: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);
ABetween 1 and 4
BOutside 1 to 4
COther
DCompilation error
Attempts:
2 left
💡 Hint
Check how the 'and' and 'or' patterns combine conditions.