-6
bool condition = true;
string input = "b";

switch (input)
{
    case "b":
        if (condition)
        {
            Console.WriteLine("B");
        }
    default:
        Console.WriteLine("Default");
        break;
}

C++:

B
Default
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
  • 1
    Those two are different languages. – Jagannath Feb 23 '15 at 06:46
  • possible duplicate of [Switch statement fallthrough in C#?](http://stackoverflow.com/questions/174155/switch-statement-fallthrough-in-c) – Jonathan Feb 23 '15 at 06:46
  • possible duplicate of [Why does C# have break if it's not optional?](http://stackoverflow.com/questions/3108888/why-does-c-sharp-have-break-if-its-not-optional) – Mahesh Feb 23 '15 at 06:46
  • 1
    C# does not allow switch case statements to flow into another case statement...its a very common C++ bug...so C# tries to protect you from it. Therefore you MUST have a `break;` in each `case`. – Aron Feb 23 '15 at 06:47
  • you must have to put a break after each case. – Jitendra Pancholi Feb 23 '15 at 06:47
  • 1
    Hm.. If `input` is `a`, why would it go in `b` case of your switch? – Pierre-Luc Pineault Feb 23 '15 at 06:48
  • You can't use strings for switches in C++ in the first place. – Biffen Feb 23 '15 at 06:53
  • 1
    And the answer is pretty simple. C++ and C# are not the same language, they implement different specs. Why would you even think about comparing their behavior? – Pierre-Luc Pineault Feb 23 '15 at 06:53
  • I would write something like switch (input) { case "b": default: if (input == "b" && condition) { Console.WriteLine("B"); } Console.WriteLine("Default"); break; } – Ako Feb 23 '15 at 12:00

1 Answers1

3

you missed a break after case,

bool condition = true;
string input = "a";
switch (input)
{
    case "b":
        if (condition)
        {
            Console.WriteLine("B");
        }
        break; // You missed break;
    default:
        Console.WriteLine("Default");
        break;
}

C# does not allow to execute more than one case which is logically incorrect so prevented by C# compiler.

Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84