Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - SWITCH WITH STRINGS


We have already seen in C# Switch - Case, the example of you being a teacher.


Now, we will look at the same example,

Example :

Say you are a class teacher and there are only 5 students in your class.

And you have marked them with their Roll Numbers and their Names.




Roll Number Name
1 Ronald
2 John
3 Murali
4 Satish
5 Debasish
Now, say the Principal of the school has asked you to write a C# program, that will show you the roll number of a student once you enter his/her name.

Code with C# Switch - Case


Example :



public class MyApplication
{
    public static void Main(string[] args)
    {
        string name = "John";

        switch (name) 
        {
            case "Ronald":
                System.Console.WriteLine("His roll number is 1");
                break;
            case "John":
                System.Console.WriteLine("His roll number is 2");
                break;
            case "Murali":
                System.Console.WriteLine("His roll number is 3");
                break;
            case "Satish":
                System.Console.WriteLine("His roll number is 4");
                break;
            case "Debasish":
                System.Console.WriteLine("His roll number is 5");
                break;
            default:
                System.Console.WriteLine("The student does not exist.");
				break;
        }
    }
}


Output :



  His roll number is 2

This time we are trying to match a String in the Switch - Case statement.


We have taken the name in a String variable name and initialised it with "John".


string name = "John";
C_Sharp


Then we have taken the name and put it in switch.


switch (name) {
	case "Ronald":
		System.Console.WriteLine("His roll number is 1");
		break;
	case "John":
		System.Console.WriteLine("His roll number is 2");
		break;
	case "Murali":
		System.Console.WriteLine("His roll number is 3");
		break;
	case "Satish":
		System.Console.WriteLine("His roll number is 4");
		break;
	case "Debasish":
		System.Console.WriteLine("His roll number is 5");
		break;
	default:
		System.Console.WriteLine("The student does not exist.");
		break;
	}

And checked which case matches "John".


And found


case "John":
	System.Console.WriteLine("His roll number is 2");
	break;

So printed John's roll number


His roll number is 2
C_Sharp