Programming Language Peculiarities – C#

It’s been extremely hard to write C# oddities because it appears the people who created it did a pretty good job. They took the best of C++ and the best of Java, put it in a cocktail shaker and out popped C#.

From a language stand point I personally think C# is excellent but prefer not to develop in it because of all the other baggage around it particularly when developing web applications. That is purely a personal preference though, although I program in high level languages I guess at heart I am quite a low level guy.

That said I did find a couple of examples that are rather interesting.

My first example is the Switch statement which doesn’t allow fall through from one case to the next for example:

switch (myVar) {
   case 1:
   case 2:
   case 3:
   default:
      System.out.println("Hello World!");
}

In Java the above would be valid however this is not valid in C#, however it is possible to mimick this behaviour but it requires slightly more code.

switch (myVar) 
{
   case 1:
     goto default;
   case 2:
     goto default;
   case 3:
     goto default;
   default:
      Console.WriteLine("Hello World!");
      break;
}

Something else to note hear is the necessity to use a break within the default because that cannot support fall through either. Some would argue that fall through is bad anyway because is removes clarity, personally I disagree with that because it reduces the repetition in code that could firstly introduce mistakes and secondly is plainly pointless.

So each case must either have a break or a return.

Something else that is unusual is that the ordering of Static variables is important, for example if you declare

// RIGHT - private static int a = 10; 
static int b = a + 5; 
// WRONG - private static int a = 10;

then a must be declared before and not after b.

The last perculiarity I will show you is simply quite amusing:

i++.toString() is allowed whereas ++i.toString() does not work unless written (++i).toString() as can be seen in the screenshot below.

So what was that error message

So in this case the compiler is trying to perform ToString() first and then increment, which is clearly not going to work.

Be the first to comment on "Programming Language Peculiarities – C#"

Leave a Reply

%d bloggers like this: