Saturday, October 20, 2007
String concatenation and null
While doing a review of a colleague's code, I happened to come across a statement similar to the one below.
I immediately flagged this is a potential problem, saying that this would throw an exception if
After talking with him in the hall after the code review, he assured me that his code worked the original way. So, I naturally pulled up Visual Studio and gave it a try, and he was right! [ This just goes to show that no matter how much one thinks he or she knows about a programming language, there is always room to learn more! ]
I looked up the
"The binary + operator performs string concatenation when on or both operands are of type string. If an operand of string concatenation is null, an empty string is subsituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted."
string myString = someVariable + "";
I immediately flagged this is a potential problem, saying that this would throw an exception if
someVariable is null. And, realizing that he was just trying to ensure that the myString is not null, I suggested doing something like the following instead.
string myString = (someVariable != null) ? someVariable : "";
After talking with him in the hall after the code review, he assured me that his code worked the original way. So, I naturally pulled up Visual Studio and gave it a try, and he was right! [ This just goes to show that no matter how much one thinks he or she knows about a programming language, there is always room to learn more! ]
I looked up the
String class in MSDN, and expected to see an overloaded + plus operator (op_Addition), but found no such thing. So, I turned to the C# spec. Sure enough, Ecma-334 section 14.7.4 states the following:"The binary + operator performs string concatenation when on or both operands are of type string. If an operand of string concatenation is null, an empty string is subsituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted."
Subscribe to Posts [Atom]