C# Example 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: 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# Example to use string with switch case statement
Output
Example 2: Here, we will input a text from the console and check whether input text starts with either "This" or "That".
Output
need an explanation for this answer? contact us directly to get an explanation for this answer