Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Switch expressions with patterns in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Switch Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of switch expression with type patterns
What is the output of the following C# code using switch expressions with type patterns?
C Sharp (C#)
object value = 42;
string result = value switch
{
    int i => $"Integer: {i}",
    string s => $"String: {s}",
    _ => "Unknown"
};
System.Console.WriteLine(result);
AString: 42
BInteger: 42
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Check the type of the variable 'value' and how the switch expression matches patterns.
❓ Predict Output
intermediate
2:00remaining
Switch expression with property pattern output
What will be printed by this C# code using a switch expression with a property pattern?
C Sharp (C#)
record Person(string Name, int Age);

Person p = new("Alice", 30);
string category = p switch
{
    { Age: < 18 } => "Minor",
    { Age: >= 18 and < 65 } => "Adult",
    { Age: >= 65 } => "Senior",
    _ => "Unknown"
};
System.Console.WriteLine(category);
AUnknown
BMinor
CSenior
DAdult
Attempts:
2 left
💡 Hint
Look at the Age property of the Person record and which pattern it matches.
🔧 Debug
advanced
2:00remaining
Identify the error in this switch expression with tuple patterns
This C# code uses a switch expression with tuple patterns. Which option correctly describes the error it produces?
C Sharp (C#)
var point = (x: 3, y: 4);
string quadrant = point switch
{
    ( > 0, > 0 ) => "First",
    ( < 0, > 0 ) => "Second",
    ( < 0, < 0 ) => "Third",
    ( > 0, < 0 ) => "Fourth",
    _ => "Origin or axis"
};
System.Console.WriteLine(quadrant);
ACompilation error due to missing parentheses around relational patterns
BRuntime NullReferenceException
COutput: First
DOutput: Origin or axis
Attempts:
2 left
💡 Hint
Check if the tuple patterns and relational patterns syntax are correct and what the values are.
📝 Syntax
advanced
2:00remaining
Which switch expression syntax is correct for matching a string prefix?
Which option shows the correct C# switch expression syntax to match a string starting with "Hello" using a pattern?
Astring greeting = input switch { string s when s.StartsWith("Hello") => "Hi", _ => "Bye" };
Bstring greeting = input switch { string s if s.StartsWith("Hello") => "Hi", _ => "Bye" };
Cstring greeting = input switch { string s => s.StartsWith("Hello") ? "Hi" : "Bye" };
Dstring greeting = input switch { string s where s.StartsWith("Hello") => "Hi", _ => "Bye" };
Attempts:
2 left
💡 Hint
Recall the correct keyword for adding a condition in a switch expression pattern is 'when'.
🚀 Application
expert
3:00remaining
Determine the number of items in the dictionary created by this switch expression
Consider this C# code that uses a switch expression inside a dictionary initializer. How many key-value pairs will the resulting dictionary contain?
C Sharp (C#)
var inputs = new object[] { 1, "two", 3.0, null };
var dict = new Dictionary<object, string>();
foreach (var item in inputs)
{
    dict[item] = item switch
    {
        int i => $"Int {i}",
        string s => $"Str {s}",
        null => "Null",
        _ => "Other"
    };
}
System.Console.WriteLine(dict.Count);
A4
B3
C2
D1
Attempts:
2 left
💡 Hint
Check how many unique keys are added to the dictionary and if any keys are overwritten.

Practice

(1/5)
1. What does a switch expression with patterns in C# primarily help you do?
easy
A. Create loops that run a fixed number of times
B. Declare variables with dynamic types
C. Match values and types cleanly without long if-else chains
D. Handle exceptions in asynchronous code

Solution

  1. Step 1: Understand switch expressions

    Switch expressions allow matching on values or types in a concise way.
  2. Step 2: Compare with if-else chains

    They replace long if-else chains with clearer, more readable code.
  3. Final Answer:

    Match values and types cleanly without long if-else chains -> Option C
  4. Quick Check:

    Switch expressions = clean matching [OK]
Hint: Switch expressions simplify matching values and types [OK]
Common Mistakes:
  • Confusing switch expressions with loops
  • Thinking switch expressions handle exceptions
  • Believing switch expressions declare variables
2. Which of the following is the correct syntax for a switch expression with a type pattern in C#?
easy
A. var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 };
B. var result = switch obj { int i => i * 2, string s => s.Length, _ => 0 };
C. var result = obj { int i => i * 2, string s => s.Length, _ => 0 } switch;
D. var result = obj switch (int i => i * 2, string s => s.Length, _ => 0);

Solution

  1. Step 1: Identify correct switch expression syntax

    The switch expression syntax is: variable switch { pattern => result, ... }.
  2. Step 2: Match options to syntax

    var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; matches this syntax exactly with type patterns and a discard pattern.
  3. Final Answer:

    var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; -> Option A
  4. Quick Check:

    Correct switch expression syntax = var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; [OK]
Hint: Remember: variable switch { patterns } is correct syntax [OK]
Common Mistakes:
  • Placing switch before the variable
  • Using parentheses instead of braces
  • Misplacing the switch keyword
3. What is the output of the following C# code?
object value = 5;
string result = value switch
{
  int i when i > 0 => "Positive integer",
  int i when i < 0 => "Negative integer",
  string s => "String",
  _ => "Unknown"
};
Console.WriteLine(result);
medium
A. Negative integer
B. Positive integer
C. String
D. Unknown

Solution

  1. Step 1: Analyze the switch expression input

    The variable 'value' is an object holding the integer 5.
  2. Step 2: Match patterns in order

    First pattern matches int i when i > 0, which is true for 5, so result is "Positive integer".
  3. Final Answer:

    Positive integer -> Option B
  4. Quick Check:

    5 > 0 matches first pattern [OK]
Hint: Check pattern order and conditions carefully [OK]
Common Mistakes:
  • Ignoring the 'when' condition
  • Assuming string pattern matches first
  • Choosing default case incorrectly
4. Identify the error in this switch expression code snippet:
object obj = "hello";
var output = obj switch
{
  int i => i.ToString(),
  string s => s.ToUpper(),
  default => "none"
};
medium
A. Patterns must be in parentheses
B. Missing semicolon after switch expression
C. Cannot switch on object type
D. Using 'default' instead of '_' for discard pattern

Solution

  1. Step 1: Check switch expression patterns

    In C# switch expressions, the discard pattern uses '_' not 'default'.
  2. Step 2: Identify the incorrect pattern usage

    The code uses 'default' which causes a syntax error; it should be '_'.
  3. Final Answer:

    Using 'default' instead of '_' for discard pattern -> Option D
  4. Quick Check:

    Discard pattern = '_' not 'default' [OK]
Hint: Use '_' for default case in switch expressions [OK]
Common Mistakes:
  • Using 'default' keyword in switch expressions
  • Confusing switch statements with switch expressions
  • Forgetting to end statements with semicolon
5. Given a list of objects, write a switch expression that returns:
- "Number" if the object is an int or double
- "Text" if the object is a non-empty string
- "Empty" if the object is an empty string
- "Other" for anything else

Which of the following switch expressions correctly implements this logic?
hard
A. obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" }
B. obj switch { int or double => "Number", string s when s == "" => "Empty", string s when s != "" => "Text", _ => "Other" }
C. obj switch { int or double => "Number", string s when s.Length > 0 => "Text", string s when s.Length == 0 => "Empty", _ => "Other" }
D. obj switch { int or double => "Number", string s when s != "" => "Text", string s when s == "" => "Empty", _ => "Other" }

Solution

  1. Step 1: Understand type patterns and conditions

    We must match int or double first, then string with length checks for empty/non-empty.
  2. Step 2: Check order and conditions

    obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } correctly checks int or double, then string with Length == 0 for "Empty", then Length > 0 for "Text", then default.
  3. Final Answer:

    obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } -> Option A
  4. Quick Check:

    Order and conditions matter in switch patterns [OK]
Hint: Order patterns from specific to general, check string length for empty [OK]
Common Mistakes:
  • Using 'or' incorrectly without parentheses
  • Checking string emptiness with == "" instead of Length
  • Placing empty string check after non-empty
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard