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

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

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Pattern 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 'when'
What is the output of the following C# code snippet?
C Sharp (C#)
object obj = 42;
string result = obj is int i && i > 40 ? "Greater than 40" : "40 or less";
Console.WriteLine(result);
A40 or less
BGreater than 40
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Check the type of obj and the condition in the 'when' clause.
Predict Output
intermediate
2:00remaining
Output of switch expression with type patterns
What will be printed by this C# code?
C Sharp (C#)
object val = 3.14;
string output = val switch
{
    int i => $"Integer: {i}",
    double d => $"Double: {d}",
    _ => "Unknown type"
};
Console.WriteLine(output);
ADouble: 3.14
BUnknown type
CInteger: 3
DCompilation error
Attempts:
2 left
💡 Hint
Look at the type of val and the matching patterns in the switch expression.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in type pattern matching
This code throws an exception at runtime. Which option correctly identifies the cause?
C Sharp (C#)
object data = null;
if (data is string s)
{
    Console.WriteLine(s.Length);
}
else
{
    Console.WriteLine("Not a string");
}
ANullReferenceException because data is null and pattern matching tries to access s.Length
BCompilation error due to missing null check
CNo exception, prints 'Not a string'
DInvalidCastException because data is null
Attempts:
2 left
💡 Hint
Consider how pattern matching with 'is' handles null values.
Predict Output
advanced
2:00remaining
Output of nested type patterns with property matching
What is the output of this C# code?
C Sharp (C#)
record Person(string Name, int Age);
object obj = new Person("Alice", 30);
string message = obj switch
{
    Person { Age: > 18 } p => $"Adult: {p.Name}",
    Person p => $"Minor: {p.Name}",
    _ => "Unknown"
};
Console.WriteLine(message);
AAdult: Alice
BMinor: Alice
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Check the property pattern and the value of Age.
🧠 Conceptual
expert
2:00remaining
Which option causes a compile-time error in type pattern usage?
Given the following code snippets, which one will cause a compile-time error?
Aif (obj is int i && i > 0) { Console.WriteLine(i); }
Bif (obj is var v && v is string s) { Console.WriteLine(s); }
Cif (obj is int or string) { Console.WriteLine("int or string"); }
Dif (obj is int i or string s) { Console.WriteLine(i + s.Length); }
Attempts:
2 left
💡 Hint
Check the syntax rules for combining patterns with 'or' and variable declarations.