Java vs C# – switch statements

This is my first installment of a new blog series I’m planning to call Java vs C#.

Today, I’ll be discussing the behavior of “switch” statements in both Java and C#.

Consider this snippet for Java which prints out the values “1”, “2” and “Default” when value = 1.

Since I did not add “break” statements after each case, it should execute the code in the next cases up to the point where it reaches a break statement (or exits the switch).

switch (value) {
   case 1:
      System.out.println("1");
   case 2:
      System.out.println("2");
   default:
      System.out.println("Default");
      break;
}

You would think that the snippet for C# below (which is patterned after the code above) would behave in exactly the same way.

switch (value)
{
   case 1: System.Console.WriteLine("1");
   case 2: System.Console.WriteLine("2");
   default: System.Console.WriteLine("Default");
      break;
}

But this is where it gets interesting, the code above will actually NOT compile.

Error 1 Control cannot fall through from one case label (‘case 1:’) to another
Error 2 Control cannot fall through from one case label (‘case 2:’) to another

They said that this is actually a safety mechanism for C# which help prevent debugging nightmares for developers in the event that these switch statements get bigger and more complex.

Seems like a valid point.

But it might be important to note that C# still allow fall through for switch statements, provided you do not add any logic to the case statements.

switch (value)
{
   case 1:
   case 2:
   default: System.Console.WriteLine("Default");
      break;
}

You can however work around the said fall through problem by using goto which I do not really recommend (so I’m not going to add any more details about that).

As a side note, in addition to int and enum types, C# switch statements also allow string types as argument.

So there you have it folks, switch statements in Java and C#.

Hope you enjoyed and learned something from my first installment.

References:

Advertisements

1 Comment »

  1. Thanks for this post.
    I was actually going to use fall through logic to help me with variable sized arrays, but now I learn that C# prohibits that.

    I disagree that this should be enforced as an illegal move by the framework, it should perhaps merely cause a Warning to give a hint “Fall through in effect from label (case 1) to (case 2)” etc.

    And I agree with you about avoiding GOTOs.

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: