Using a string with a switch case statement in C#

C# Example to use a string with a 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...
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...

Leave a Comment

error: Alert: Content is protected!!