Home > Software engineering >  I have a problem with: switch case condition [closed]
I have a problem with: switch case condition [closed]

Time:10-05

I got a task from computer science lesson to write a program that gets my name and if it's my real name then write welcome, else write access denied (it must be with switch case condition) but I got a problem with the switch case condition:

Console.Write("type your name: ");
        string name = Console.ReadLine();

        switch (name)
        {
            case name == "lior": Console.WriteLine("welcome");
            case name != "lior": Console.WriteLine("access denied");
        }

click here for image

CodePudding user response:

        case "lior": 
          Console.WriteLine("welcome");
          break;
        default: 
          Console.WriteLine("access denied");
          break;

Switch is typically used when there are many different options. Here it is only two options: your name and not your name. So you could just use if/else.

CodePudding user response:

To amend existing case you should add break:

    switch (name)
    {
        case name == "lior": 
            Console.WriteLine("welcome");
                
            break;  

        case name != "lior": 
            Console.WriteLine("access denied");

            break; 
    }

But you can use a simple alternative, ternary operator:

    Console.Write("type your name: ");

    string name = Console.ReadLine();

    Console.WriteLine(name == "lior" ? "welcome" : "access denied");
  •  Tags:  
  • c#
  • Related