C# - String with Switch Case Statement

C# string with switch case: Here, we are going to learn how to use string with the switch case statement in C#?
Submitted by IncludeHelp, on March 17, 2019 [Last updated : March 18, 2023]

C# string with switch case statement

In C# programming language – we can use a string with the switch case statement, switch case statement is a type of selection control mechanism, which is used to execute a block from multiple blocks. Switch case multiple blocks and a variable/value, when value matches with the case, the body of the case associated with that case is executed.

Note: break must be used with all switch case blocks including default.

C# program to use string with switch case statement

using System; using System.Text; namespace Test { class Program { static void Main(string[] args) { string gender = "Male"; switch (gender) { case "Male": Console.WriteLine("He is male..."); break; case "Female": Console.WriteLine("She is female..."); break; default: Console.WriteLine("Default"); break; } //hit ENTER to exit Console.ReadLine(); } } }

Output

He is male...

Example 2: C# string with switch case statement

Here, we will input a text from the console and check whether input text starts with either "This" or "That".

using System; using System.Text; namespace Test { class Program { static void Main(string[] args) { string text = ""; Console.Write("Enter some text: "); text = Console.ReadLine(); switch (text.Substring(0, 4)) { case "This": Console.WriteLine("text started with \"This\""); break; case "That": Console.WriteLine("text started with \"That\""); break; default: Console.WriteLine("Invalid text..."); break; } //hit ENTER to exit Console.ReadLine(); } } }

Output

First run:
Enter some text: This is a game.
text started with "This"

Second run:
Enter some text: That is a book.
text started with "That"

Third run:
Enter some text: These are cows.
Invalid text...

C# Basic Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.