Posts Tagged C#

Pro C# 2008 for $10

At 12:01 AM PST, a different Apress or friends of ED eBook will be priced at $10 US for a 24-hour period

You can view/purchase the discounted eBooks from this URL: http://www.apress.com/info/dailydeal.

I already have four books from that promo, including Pro C# 2008 which I purchased also for $10 last January 24.

1590598849 Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition

Luckily, they are featuring that book again for $10.

So hurry, buy now before time runs out…

UPDATE 4/1: Deal’s off, price is back up to $41.99.

Buying directly from Amazon might be the better option. Better luck next time.

Advertisements

Leave a Comment

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:

Comments (1)