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

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

Choose your learning style9 modes available
Using Constant Patterns in C#
📖 Scenario: You are building a simple program that checks the type of fruit and prints a message based on the fruit name.
🎯 Goal: Learn how to use constant patterns with switch expressions in C# to match exact values.
📋 What You'll Learn
Create a string variable called fruit with a specific fruit name.
Create a switch expression using constant patterns to check the fruit.
Print a message for each fruit using Console.WriteLine.
💡 Why This Matters
🌍 Real World
Constant patterns help you check exact values easily, like checking user input or commands in programs.
💼 Career
Understanding constant patterns is useful for writing clear and concise code in many C# applications, including web, desktop, and game development.
Progress0 / 4 steps
1
Create the fruit variable
Create a string variable called fruit and set it to the value "Apple".
C Sharp (C#)
Need a hint?

Use string fruit = "Apple"; to create the variable.

2
Create a switch expression with constant patterns
Create a variable called message and assign it a switch expression that matches fruit using constant patterns for "Apple", "Banana", and "Orange". For each fruit, return a message like "You chose Apple". Use _ as the default pattern returning "Unknown fruit".
C Sharp (C#)
Need a hint?

Use the switch expression syntax with constant patterns like "Apple" => "You chose Apple".

3
Add a Console.WriteLine to print the message
Use Console.WriteLine to print the message variable.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(message); to display the message.

4
Test with a different fruit value
Change the value of fruit to "Grape" and run the program to see the default message "Unknown fruit" printed.
C Sharp (C#)
Need a hint?

Set fruit to "Grape" and run the program to see the default case message.