Disclaimer: This is a personal web page. Contents written here do not represent the position of my employer.

Wednesday, February 04, 2009


My first .NET runtime wishlist item

Heh, I came up with this while coding a patch for Banshee:

public class TestStaticInits
  public static readonly X var = new X ("Hello" + world);
  private static string world = " World";

public class X
  public X (string s)
    Console.WriteLine (s);

  public override string ToString () { return "Bye"; }

public class WishList
  public static int Main(string[] args)
    Console.WriteLine (TestStaticInits.var.ToString ());
    return 0;

Shouldn't this print Hello World instead of just Hello? Basic initializations should have more priority than those involving constructors :)

At least it works if you replace the second static with const... But this confused me a bit for a while. So definitely something the compiler could warn about (ok, Gendarme is another candidate too).

UPDATE: And anyway, if we accept that our runtime is not so clever, it should give a NRE instead of printing Hello, right? You cannot concatenate a string with null. So is this a .NET bug?

UPDATE: Doh! I could have sworn that I got a lot of NRE's in the past when coding this Console.WriteLine ("Hey" + null); (I mean, when using a var and not protecting against null). Thanks for all the comments.

Labels: , , ,

This page is powered by Blogger. Isn't yours?


RSS of the category Gnome
RSS of the category Mono
RSS of the category C#
RSS of the category Programming
RSS of the category Mozilla
RSS of the category Web Development
RSS of the category Security
RSS of the category Open Source
RSS of the category Engineering
RSS of the category Misc
RSS of the category Politics

Contact with me:

My Photo
Location: Hong Kong, Hong Kong
Follow me on Twitter