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

Why pattern matching matters in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why pattern matching matters
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Use Console.WriteLine($"Total discount: {totalDiscount}"); to print the result.