Why Does This C# Code Compile?

by Joey deVilla on November 28, 2008

Here’s a cute little puzzler I got from the blog hackification — why the does code below compile?

Here’s what the output of the program looks like:

Console output: "Hello from Global Nerdy! (Press ENTER to continue)"

Why does the program compile even though the first line of the Main() method is a “bareword” URL? See if you can figure it out on your own rather than running it through the compiler – doing that gives away the answer.

I’ll post the answer in the comments.

{ 6 comments… read them below or add one }

1 Joey deVilla November 28, 2008 at 7:33 pm

The Asnwer:
The compiler interprets the line http://www.globalnerdy.com this way:

  • http: is a label.
  • //www.globalnerdy.com is a comment.
2 Enrico November 28, 2008 at 7:39 pm

That was my first guess and I’ve never done anything with C#. Still a neat little puzzle though. =)

3 Danny V November 28, 2008 at 8:33 pm

I guess the simplest answer is correct. I was thinking that maybe C# parses URLs in some way but the label-comment combo came to mind too.

4 David Janes November 28, 2008 at 8:39 pm

Label? Does C# have GOTOs?

5 Joey deVilla November 28, 2008 at 11:30 pm

@David Janes: Yup, there’s a goto statement in C#.

C# also has the break and continue keywords, but unlike Java, they don’t support labels and are limited to breaking out of or starting at the next iteration of the current loop. That’s what C#’s goto (which java doesn’t have) is for.

6 Ry4an November 29, 2008 at 12:05 pm

I first saw this in the Java Puzzlers book. Full of fun little compiler oddities.

Leave a Comment

Previous post:

Next post: