5

Recently, I've seen the following statement quite a lot:

object o;
// assign o
return "" + o;

(Basically the same as return String.Concat(o);)

Why would anyone want to do that? Why not just call .ToString() on the object (after checking object is not null, of course)?

Sure, the code is shorter and does away with the null check, but I find it confusing to read. Are there any other benefits to this? I've also seen the same statement with regard to integer values.

I expect to see above code in loosely typed languages such as JavaScript or PHP – but not in C#.

1
  • IMO "+" operator for concatenation is always not so clear but well this may be a too extreme position... Commented Oct 29, 2013 at 14:15

2 Answers 2

4

IMO, Just a bad approach to avoid Null Reference Exception.

Probably the original developer's intent was to use as less code as possible in returning string without checking null or Type

Sign up to request clarification or add additional context in comments.

Comments

3

No, you would not want to do that in C#. You are better off with calling the ToString method on the object. There are some languages where that is the preferred syntax, such as with JavaScript. So you might be seeing some cross-language leak.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.