Programming Language Peculiarities — C#
Zone Leader Brett Crawley returns with the programming language peculiarities series, this time looking at C#!
Join the DZone community and get the full member experience.
Join For FreeIt'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 mimic 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;
}
[Editor's note: this isn't actually necessary in C# (switch cases do fall through), so we'll update the article shortly. Thanks to Brian Friesen for pointing this out.]
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.
Opinions expressed by DZone contributors are their own.
Comments