简体   繁体   中英

Checking string value of variable in switch case using c#

i am checking that variable username contain "ali" which is string value in switch case but my teacher told me earlier that you can only check data-type char and int but it is working fine with string so i am confused that checking string data-type in switch is good practice or not?

string userName = "Ali";//the variable i want to check

switch(userName)
{
  case "Ali"://value i want to check
  Console.WriteLine("found");
  break;

  default:
  Console.WriteLine("not found");
  break;

}

You most certainly can use a string in a switch expression.

In C# 6.0 you could use integral values, enums, booleans, chars and yes, strings. Since C# 7.0 you can use any non-null expression. See the official documentation for additional details.

Yes, you can do it. But not the way you try to do. Your string in switch is in uppercase but variable isn't. Also your variable named userNAme but in switch you try to use userName . Try this code:

string userName = "Ali";

switch(userName.ToLower()) 
{
    case "ali":
        Console.WriteLine("found");
        break;
    default:
        Console.WriteLine("not found");
        break;
}

You can use flow control switch for the string

but you find two error in your coding, because c# case sensitive

string userNAme and and you write switch(userName)

and

break: change to break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM