Monday, September 10, 2007

string + string

A coworker discovered a strange C# language "feature" today.

Take a look a the following code:
string n1 = null, n2 = null;
string s = n1 + n2;

What's the value of s?

I would have expected it to be null, but its not, its String.Empty.

At first I thought this was a feature to avoid a null reference error, but I was confusing C# and C++. In C++ operator overloads are member methods, so they can't be called if the object is null.

However, in C# operator overloads are static methods, so it doesn't matter if the objects are null:
public class NullOp
{
public static NullOp operator + ( NullOp no1, NullOp no2 )
{ ... }
}


Since that doesn't explain this behavior, I have no idea why they designed C# to work this way. Its very interesting.

1 comment:

  1. Totally unrelated to this post but if you still want to pick up pragmatic programmer there is a used book store on euclid ave in willoughby that has it for 10 bucks (retail price 50)

    ReplyDelete

Note: Only a member of this blog may post a comment.