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

Positional patterns in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Positional Patterns in C#
📖 Scenario: You work at a delivery company that handles different types of packages. Each package has a type and a weight. You want to write a program that checks the package type and weight to decide how to handle it.
🎯 Goal: Build a C# program that uses positional patterns to check package details and print the handling instructions.
📋 What You'll Learn
Create a record type Package with two properties: Type (string) and Weight (int).
Create a variable package with specific values.
Create a variable maxWeight to set the weight limit.
Use a switch expression with positional patterns to decide the handling message.
Print the handling message.
💡 Why This Matters
🌍 Real World
Delivery companies often need to decide how to handle packages based on their type and weight. Using positional patterns helps write clear and concise code for these decisions.
💼 Career
Understanding positional patterns and switch expressions is useful for writing clean, readable C# code in many business applications, especially those involving data classification and decision making.
Progress0 / 4 steps
1
Create the Package record and a package instance
Create a record called Package with two properties: string Type and int Weight. Then create a variable called package and set it to new Package("Fragile", 15).
C Sharp (C#)
Need a hint?

Use the record keyword to create a simple data container with two properties.

2
Add a maxWeight variable
Add an integer variable called maxWeight and set it to 20.
C Sharp (C#)
Need a hint?

This variable will be used to compare the package weight later.

3
Use a switch expression with positional patterns
Create a string variable called handling and set it using a switch expression on package. Use positional patterns to match Type and Weight as follows: if Type is "Fragile" and Weight is less than or equal to maxWeight, set handling to "Handle with care"; if Type is "Heavy" and Weight is greater than maxWeight, set handling to "Use forklift"; otherwise, set handling to "Standard handling".
C Sharp (C#)
Need a hint?

Use the switch expression with positional patterns and when clauses for conditions.

4
Print the handling message
Write a Console.WriteLine statement to print the handling variable.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(handling); to show the result.