Will the following C# compile?

While reviewing some code earlier his week, I came across a C# function which when reduced to its core essentials boiled down to the following sample:

public void SomeMethod()

     MessageBox.Show("hello world");

Off the top of your head do you think a C# compiler would happily accept this source code, or would you expect a syntax error?

The answer is that the above example function is completely valid C# source code. It is easier to see why once syntax highlighting has been applied to it.

The // characters after the http: prefix cause the rest of the URL to be interpreted as a comment, and the bit which is left (http:) is in the correct syntax to be interpreted as a label for use with the goto statement.

I had accidentally pasted a URL into my source code and checked it into our source control system. I didn’t notice for a few weeks since the code compiled and executed perfectly…

An amusing (but somewhat useless) application of this fact can be found in the following program

using System;
public class MyDumbApplication
  public static void Main() 
     Console.WriteLine("Hello World!");  
     goto http; 

I wonder if this fact could be used to advantage in a International Obfuscated C Code Contest style C# program?

2 Responses to “Will the following C# compile?”

  1. So strange, this happened to me today!

  2. Simeon says:

    That’s so fluky, makes sense once you dissect it, but I couldn’t see pasts the “ITS WRONG” thinking.

Leave a Reply