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

Switch expressions with patterns in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Switch Expressions with Patterns
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

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