Why does my switch statement works differently?

Published 22 July 04 05:50 PM

C# does not support an explicit fall through for case blocks (unless the block is empty) 

For an explanation of why, see Why is the C# switch statement designed to not allow fall through, but still require a break? on MSDN

The following code is not legal and will not compile in C#:

switch (x)

{

case 0:

Console.WriteLine(x)

// do something

case 1:

Console.WriteLine(x)

// do something in common with 0

default:

Console.WriteLine(x)

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

break;

}

In order to achieve the same effect in C# the code must be modified as shown below (notice how the control flows are very explicit): 

class Test

{

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;

}

}

}

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Cook Computing said on July 23, 2004 4:22 AM:
The C# switch statement does not allow you to drop through case blocks unless the block is empty. So how do you share the same code for more than one case? The C# Frequently Asked Questions blog provides the answer:class...
# m said on August 1, 2004 12:31 PM:
asas
# RebelGeekz said on December 28, 2004 4:54 AM:
[http://itpeixun.51.net/][http://aissl.51.net/][http://kukuxz003.freewebpage.org/][http://kukuxz001.51.net/][http://kukuxz003.51.net/][http://kukuxz005.51.net/][http://kukuxz002.51.net/][http://kukuxz004.freewebpage.org/][http://kukuxz007.51.net/][http://kukuxz001.freewebpage.org/][http://kukuxz006.51.net/][http://kukuxz002.freewebpage.org/][http://kukuxz004.51.net/][http://kukuxz008.51.net/][http://kukuxz009.51.net/][http://kukuxz005.freewebpage.org/][http://kukuxz006.freewebpage.org/][http://kukuxz007.freewebpage.org/][http://kukuxz009.freewebpage.org/]
# FAQ C# said on May 2, 2005 11:03 AM:
# FAQ C# (par Yannick Lejeune) said on August 23, 2005 5:14 AM:

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker