Tech Off Post

Single Post Permalink

View Thread: null + null = ?
  • User profile image

    I think I jumped the gun a little too quick on this one. I didn't look at the IL. Obviously what happened here is that C# compiler decided that null + null was a constant expression and substitued it with an empty string.

    So it was the C# compiler that decided that the type of the null references concatenation was 'string'. I'm not sure where this behavior would be documented, but I'm sure it would be..

    You can't compile something like this:

          object a = null;
          object b = null;
          Console.WriteLine((a + b).GetType());

    Nor can you compile something like this:

      public class MyType {
        public static MyType operator + (object a, object b) {
          // ..

    I can't imagine any other 'null + null' case that the CLR might actually see at runtime (i.e. where the type information was missing). With the type information present there are rules for determining which operator overload will get called..

    So, this is a C# language feature it would seem. I wonder what happens in other .NET languages..