My switch statement works differently! Why?

C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#: switch(x)

{

case 0:

// do something

case 1:

// do something in common with 0

default:

// do something in common with

//0, 1 and everything else

break;

}

To achieve the same effect in C#, the code must be modified as shown

below (notice how the control flows are explicit): class Test

{

public static void Main()

{

int x = 3;

switch(x)

{

case 0:

// do something

goto case 1;

case 1:

// do something in common with 0

goto default;

default:

// do something in common with 0, 1, and anything else

break;

}

}

}

Showing Answers 1 - 24 of 24 Answers

sunil mittal

  • Jul 6th, 2007
 

switch (x)

{

case 1:

Console.WriteLine("1");

Console.Read();break;

case 2:

Console.WriteLine("2");

Console.Read();

break;

default :

Console.WriteLine("default");

Console.Read();

break;

}
This will work

jitendra kumar

  • Jul 10th, 2007
 

This is right that this example works, but it is not related to fall through.

Fall through means if you didn't write any statement in case 0, control automatically go to next case, which is not supported by c#, and we need to use goto statement to send control to next case.

  Was this answer useful?  Yes

Rashmita

  • Jul 19th, 2007
 

Very true ..
You have to write goto statement within the case to transfer the flow to the next switch case block..

  Was this answer useful?  Yes

pritam83

  • Sep 21st, 2007
 

Actually in C# if we use switch case then according to the value of the switch variable the pointer will move to that desired case. But it is not possible that if you are not writing anything in case 0: then the pointer will not move to the second case.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions