📖 Scenario: You are building a simple program that identifies the type of a shape based on its properties. This is like sorting different objects by looking at their features.
🎯 Goal: Create a program that uses switch with pattern matching to identify shapes by their properties.
📋 What You'll Learn
Create a variable called shape with a value representing a shape object.
Create a variable called description to hold the shape description.
Use a switch expression with pattern matching on shape.
Print the description to the console.
💡 Why This Matters
🌍 Real World
Pattern matching helps you write clear code that decides actions based on object properties, like sorting shapes or handling different user inputs.
💼 Career
Understanding pattern matching in switch statements is useful for writing clean, readable code in C# applications, especially in UI, data processing, and game development.
Progress0 / 4 steps
1
Create the shape variable
Create a variable called shape and assign it the value new { Sides = 3, Name = "Triangle" }.
C Sharp (C#)
Hint
Use var shape = new { Sides = 3, Name = "Triangle" }; to create an anonymous object.
2
Create the description variable
Create a variable called description and set it to an empty string "".
C Sharp (C#)
Hint
Use string description = ""; to create an empty string variable.
3
Use switch with pattern matching
Use a switch expression on shape to set description as follows: - If shape.Sides is 3, set description to "Triangle". - If shape.Sides is 4, set description to "Quadrilateral". - Otherwise, set description to "Unknown shape".
C Sharp (C#)
Hint
Use switch with pattern matching like shape switch { { Sides: 3 } => "Triangle", ... }.
4
Print the description
Write a Console.WriteLine statement to print the description variable.
C Sharp (C#)
Hint
Use Console.WriteLine(description); to print the result.
Practice
(1/5)
1. What does pattern matching in a switch statement primarily help you do in C#?
easy
A. Check an object's type and properties in a clear way
B. Loop through collections more efficiently
C. Declare variables with less code
D. Handle exceptions automatically
Solution
Step 1: Understand pattern matching purpose
Pattern matching in switch lets you test an object's type and properties clearly.
Step 2: Compare with other options
Looping, variable declaration, and exception handling are unrelated to pattern matching in switch.
Final Answer:
Check an object's type and properties in a clear way -> Option A
Quick Check:
Pattern matching = type and property checks [OK]
Hint: Pattern matching checks types and conditions clearly [OK]
Common Mistakes:
Confusing pattern matching with loops
Thinking it handles exceptions
Believing it declares variables automatically
2. Which of the following is the correct syntax to match an integer variable num equal to 10 using pattern matching in a switch expression?
easy
A. case int n when n == 10:
B. case int n == 10:
C. case int n => 10:
D. case int n is 10:
Solution
Step 1: Recall correct pattern matching syntax
To match a value with a condition, use case Type variable when condition:.
Step 2: Check each option
case int n when n == 10: uses when n == 10, which is correct. Others use invalid syntax.
Final Answer:
case int n when n == 10: -> Option A
Quick Check:
Use 'when' for conditions in pattern matching [OK]
Hint: Use 'when' keyword for conditions in switch patterns [OK]
Common Mistakes:
Using '==' directly after case without 'when'
Using '=>' or 'is' incorrectly in case
Omitting the variable name
3. What will be the output of this C# code?
object obj = 42;
switch (obj)
{
case int n when n > 40:
Console.WriteLine("Greater than 40");
break;
case int n:
Console.WriteLine("Integer");
break;
default:
Console.WriteLine("Other");
break;
}
medium
A. Integer
B. Other
C. Greater than 40
D. No output (compile error)
Solution
Step 1: Identify the object type and value
obj is an integer with value 42.
Step 2: Evaluate switch cases in order
First case matches int n when n > 40, which is true for 42, so prints "Greater than 40" and breaks.
Final Answer:
Greater than 40 -> Option C
Quick Check:
Pattern with 'when' matched first [OK]
Hint: Check cases top to bottom; first match runs [OK]
Common Mistakes:
Ignoring the 'when' condition
Assuming second case runs first
Thinking default runs for int
4. Identify the error in this switch statement using pattern matching:
object val = "hello";
switch (val)
{
case string s when s.Length > 3
Console.WriteLine("Long string");
break;
default:
Console.WriteLine("Other");
break;
}
medium
A. Cannot use 'when' with string type
B. Missing colon ':' after case pattern
C. Missing parentheses around condition
D. Incorrect variable name in case
Solution
Step 1: Check switch case syntax
Each case pattern must end with a colon ':' before the statements.
Step 2: Locate missing colon
The case line lacks ':' after when s.Length > 3, causing syntax error.
Final Answer:
Missing colon ':' after case pattern -> Option B
Quick Check:
Case patterns need ':' after condition [OK]
Hint: Always put ':' after case pattern line [OK]
Common Mistakes:
Forgetting ':' after case pattern
Adding parentheses around 'when' condition
Thinking 'when' can't be used with strings
5. Given a list of objects items containing integers and strings, how would you use pattern matching in a switch expression to return a new list of strings where: - Integers greater than 10 become "Big number" - Strings longer than 5 characters become "Long text" - All others become "Other"?
Which code snippet correctly implements this?
hard
A. items.Select(item => item switch {
int n when n > 10: "Big number",
string s when s.Length > 5: "Long text",
_ => "Other"
}).ToList();
B. items.Select(item => switch (item) {
case int n if n > 10: "Big number";
case string s if s.Length > 5: "Long text";
default: "Other";
}).ToList();
C. items.Select(item => item switch {
int n if n > 10: "Big number",
string s if s.Length > 5: "Long text",
_ => "Other"
}).ToList();
D. items.Select(item => item switch {
int n when n > 10 => "Big number",
string s when s.Length > 5 => "Long text",
_ => "Other"
}).ToList();
Solution
Step 1: Understand switch expression syntax
Switch expressions use '=>' for cases, and 'when' for conditions.
Step 2: Check each option's syntax
items.Select(item => item switch {
int n when n > 10 => "Big number",
string s when s.Length > 5 => "Long text",
_ => "Other"
}).ToList(); uses correct 'item switch { case => result }' with 'when' and '=>'. Other options use invalid syntax ('switch' inside lambda or 'if' instead of 'when'). items.Select(item => item switch {
int n when n > 10: "Big number",
string s when s.Length > 5: "Long text",
_ => "Other"
}).ToList(); uses ':' instead of '=>', which is invalid in switch expressions.
Final Answer:
items.Select(item => item switch {
int n when n > 10 => "Big number",
string s when s.Length > 5 => "Long text",
_ => "Other"
}).ToList(); -> Option D
Quick Check:
Switch expressions use '=>' and 'when' [OK]
Hint: Use '=>' and 'when' in switch expressions for conditions [OK]
Common Mistakes:
Using ':' instead of '=>' in switch expressions
Using 'if' instead of 'when' for conditions
Trying to put 'switch' keyword inside lambda
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.