📖 Scenario: You are building a simple program that describes animals based on their type and age. This helps a zoo staff quickly understand animal details.
🎯 Goal: Create a C# program that uses a switch expression with patterns to return descriptions for different animals.
📋 What You'll Learn
Create a record called Animal with properties Type (string) and Age (int).
Create an Animal variable with specific values.
Create a switch expression using pattern matching on the Animal variable.
Print the description returned by the switch expression.
💡 Why This Matters
🌍 Real World
Pattern matching with switch expressions helps write clear and concise code when you want to handle different cases based on object properties, like categorizing animals or processing user input.
💼 Career
Many C# jobs require understanding modern language features like switch expressions and pattern matching to write clean, maintainable code.
Progress0 / 4 steps
1
Create the Animal record and an instance
Create a record called Animal with properties Type (string) and Age (int). Then create a variable called animal and set it to new Animal("Dog", 5).
C Sharp (C#)
Hint
Use the record keyword to create Animal. Then create animal with new Animal("Dog", 5).
2
Create a variable for the description using switch expression
Create a variable called description and assign it a switch expression on animal. Use pattern matching with Animal to match these cases: Type == "Dog" and Age < 3 returns "Puppy Dog", Type == "Dog" and Age >= 3 returns "Adult Dog", Type == "Cat" returns "Cat", and a default case returns "Unknown Animal".
C Sharp (C#)
Hint
Use a switch expression with pattern matching on animal. Use property patterns like Animal { Type: "Dog", Age: < 3 }.
3
Change the animal to a Cat aged 2
Change the animal variable to new Animal("Cat", 2).
C Sharp (C#)
Hint
Just replace the animal variable assignment with new Animal("Cat", 2).
4
Print the description
Write a Console.WriteLine statement to print the description variable.
C Sharp (C#)
Hint
Use Console.WriteLine(description); to show the result.
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
Step 1: Understand switch expressions
Switch expressions allow matching on values or types in a concise way.
Step 2: Compare with if-else chains
They replace long if-else chains with clearer, more readable code.
Final Answer:
Match values and types cleanly without long if-else chains -> Option C
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
Step 1: Identify correct switch expression syntax
The switch expression syntax is: variable switch { pattern => result, ... }.
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.
Final Answer:
var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; -> Option A
Quick Check:
Correct switch expression syntax = var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; [OK]
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
Step 1: Analyze the switch expression input
The variable 'value' is an object holding the integer 5.
Step 2: Match patterns in order
First pattern matches int i when i > 0, which is true for 5, so result is "Positive integer".
Final Answer:
Positive integer -> Option B
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
Step 1: Check switch expression patterns
In C# switch expressions, the discard pattern uses '_' not 'default'.
Step 2: Identify the incorrect pattern usage
The code uses 'default' which causes a syntax error; it should be '_'.
Final Answer:
Using 'default' instead of '_' for discard pattern -> Option D
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
Step 1: Understand type patterns and conditions
We must match int or double first, then string with length checks for empty/non-empty.
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.
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
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 unknownstrongwhile earning +1 Grip toward your certificate.