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

Pattern matching in switch in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Pattern matching in switch
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Use Console.WriteLine(description); to print the result.