📖 Scenario: Imagine you work at a store that sells different types of products. Each product has a different way to calculate its discount. You want to write a program that checks the product type and calculates the discount correctly.
🎯 Goal: You will build a simple program that uses pattern matching to check product types and calculate discounts easily and clearly.
📋 What You'll Learn
Create a list of products with different types
Create a variable to hold the total discount
Use pattern matching with switch expressions to calculate discounts based on product type
Print the total discount
💡 Why This Matters
🌍 Real World
Pattern matching helps write clear and simple code when you have different types of data that need different handling, like products with different discount rules.
💼 Career
Many jobs require handling different data types and making decisions based on them. Pattern matching is a modern, readable way to do this in C#.
Progress0 / 4 steps
1
Create product classes and a list
Create three classes called Book, Food, and Clothing. Each class should have a public property Price of type decimal. Then create a list called products containing these exact items: a Book with price 20.0m, a Food with price 10.0m, and a Clothing with price 50.0m.
C Sharp (C#)
Hint
Define each class with a Price property. Then create a list of type object and add one instance of each class with the given prices.
2
Create a variable to hold total discount
Inside the Main method, create a variable called totalDiscount of type decimal and set it to 0.
C Sharp (C#)
Hint
Use decimal totalDiscount = 0m; to create the variable.
3
Calculate discounts using pattern matching
Use a foreach loop with variable product to go through products. Inside the loop, use a switch expression with pattern matching on product to calculate a discount: if product is Book, discount is 10% of Price; if Food, discount is 5% of Price; if Clothing, discount is 20% of Price; otherwise, discount is 0. Add each discount to totalDiscount.
C Sharp (C#)
Hint
Use foreach (object product in products) and a switch expression with pattern matching to calculate discounts.
4
Print the total discount
Write a Console.WriteLine statement to print the text Total discount: followed by the value of totalDiscount.
C Sharp (C#)
Hint
Use Console.WriteLine($"Total discount: {totalDiscount}"); to print the result.
Practice
(1/5)
1. What is the main benefit of using pattern matching in C#?
easy
A. It simplifies checking types and extracting data in one step.
B. It makes the program run faster by optimizing CPU usage.
C. It automatically fixes syntax errors in the code.
D. It replaces all loops with recursive calls.
Solution
Step 1: Understand pattern matching purpose
Pattern matching lets you check a variable's type and extract its data in a single, clear step.
Step 2: Compare with other options
Options A, B, and D describe unrelated or incorrect benefits not provided by pattern matching.
Final Answer:
It simplifies checking types and extracting data in one step. -> Option A
Quick Check:
Pattern matching = Simplifies type checks [OK]
Hint: Pattern matching combines type check and data use in one step [OK]
Common Mistakes:
Thinking pattern matching speeds up CPU performance
Confusing pattern matching with syntax error fixing
Believing pattern matching replaces loops
2. Which of the following is the correct syntax for pattern matching with is in C#?
easy
A. if (obj is int number) { /* use number */ }
B. if (obj is int) number { /* use number */ }
C. if (obj is int: number) { /* use number */ }
D. if (obj int is number) { /* use number */ }
Solution
Step 1: Recall correct pattern matching syntax
The correct syntax uses is Type variable inside the if condition, like obj is int number.
Step 2: Identify syntax errors in other options
Options A, B, and C have incorrect order or punctuation that cause syntax errors.
Final Answer:
if (obj is int number) { /* use number */ } -> Option A
Quick Check:
Correct pattern matching syntax = if (obj is int number) { /* use number */ } [OK]
Hint: Remember: 'is Type variable' is the pattern matching syntax [OK]
Common Mistakes:
Placing variable before type in 'is' expression
Using colon ':' instead of space
Mixing order of keywords
3. What will be the output of this code?
object obj = 42;
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}
medium
A. String: 42
B. Integer: 42
C. Unknown type
D. Compilation error
Solution
Step 1: Identify the type of obj
obj is assigned the integer value 42, so its runtime type is int.
Step 2: Match switch cases
The switch matches case int i because obj is an int, so it prints "Integer: 42".
Final Answer:
Integer: 42 -> Option B
Quick Check:
obj is int 42, so output = "Integer: 42" [OK]
Hint: Match the runtime type to the correct case in switch [OK]
Common Mistakes:
Assuming obj is string because of quotes missing
Thinking default case runs first
Confusing compile-time and runtime types
4. Identify the error in this pattern matching code:
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
medium
A. The variable 'number' is not declared before use.
B. The 'is' keyword cannot be used with variables.
C. Missing braces around the if block.
D. The pattern matching condition will never be true for a string.
Solution
Step 1: Analyze the type of obj
obj holds a string "hello", but the pattern checks if obj is an int.
Step 2: Understand pattern matching behavior
Since obj is a string, the condition obj is int number is false, so the block never runs.
Final Answer:
The pattern matching condition will never be true for a string. -> Option D
Quick Check:
obj is string, pattern checks int, so condition false [OK]
Hint: Check if variable type matches pattern type before using it [OK]
Common Mistakes:
Assuming variable 'number' must be declared separately
Thinking 'is' cannot be used with variables
Ignoring that condition can be false without error
5. Given a list of objects List<object> items = new() { 1, -2, "two", 3.0, null };, which pattern matching expression correctly counts only the positive integer values?
hard
A. items.Count(item => item is string s)
B. items.Count(item => item is int)
C. items.Count(item => item is int number && number > 0)
D. items.Count(item => item != null)
Solution
Step 1: Understand the goal
We want to count only positive integers in the list, ignoring other types and null.
Step 2: Analyze each option
items.Count(item => item is int) counts all ints but does not filter by value; items.Count(item => item is int number && number > 0) counts ints greater than 0, which matches positive integers; items.Count(item => item is string s) counts strings; items.Count(item => item != null) counts all non-null items.
Step 3: Choose the best option
items.Count(item => item is int number && number > 0) uses pattern matching with a condition to count only positive integers, which is a precise use of pattern matching.
Final Answer:
items.Count(item => item is int number && number > 0) -> Option C
Quick Check:
Pattern matching with condition filters integers correctly [OK]
Hint: Use 'is Type var && condition' to filter precisely [OK]
Common Mistakes:
Counting all ints without condition when needed
Counting strings or non-null items by mistake
Not using variable in pattern matching for conditions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.