Embed URL’s directly into your C# code

Ok, so this isn’t strictly a language feature and it’s not terribly useful either, but it did cause me to do a double-take when it compiled with no errors.

I had cut and pasted a URL into the block of code I was currently working on, so I could refer to it more easily. However, I accidentally left it there when I compiled the program, and to my dismay it compiled without complaint! Take the following contrived code block for example: 

public int Add( int x, int y )
    int result = x + y;
    return result;

The URL just dumped into the middle of a block of code should certainly have caused some kind of compiler error, right? Or should it…?

In C# (and C++), everything after the “//” is treated as a comment and is therefore ignored. So the compiler will never see “windowscheerleader.com/”. But that still leaves us with “http:” in the middle of the code.

However, it turns out that the compiler thinks the “http:” is a label – the destination for a goto command! In other words, we could write another silly function like the one below, and the compiler would be perfectly happy with it!

public int GetSmallerValue( int x, int y )
    if ( x < y )
        goto http;
    return y;
    return x;

As far as the compiler is concerned, we have a label followed by a comment, which is perfectly valid. As I said earlier, this isn’t terribly useful (unless you want to embed uncommented URL’s into your code for some reason), but I did find it interesting. One word of warning though – since the “http:” is a label, you can only use this “technique” once in each scoped block or the complier will get upset with you!


3 responses to “Embed URL’s directly into your C# code

  1. While I would never use this in code it is quite amusing that it works 🙂 .

  2. It’s not really amusing. It works because it’s valid. http: IS a label. and //whatever IS a comment. This could be used to embed the URL of a support document or debug file. Why? If the application crashes and you view the code in a debugger you’ll see the link to the support. I’ve seen this done in applications like Pidgeon and Chrome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s