Difference between x.toString() and x+“”

后端 未结 8 1993
暗喜
暗喜 2020-12-11 22:50

Back in college one of my profs. taught us to just do x + \"\" as a quick conversion from basic types to strings.
I don\'t remember which class it was in I

8条回答
  •  攒了一身酷
    2020-12-11 23:35

    Honestly, I consider that kind of weird advice.

    I can't speak to every specific case, but in general what x + "" will do in C# (which should depend on the existence of an overloaded + operator for either the type of x or string) is call something like string.Concat(x, "") which in turn will invoke x.ToString anyway.

    In the typical case, this just means that x + "" has the overhead of one more method call than x.ToString. When x is a variable of some value type, however, this can also cause the value of x to be boxed unless an overload for + exists specifically for the type of x (this might be considered a useless point to make, as x will also be boxed in a call to ToString if its type has not overridden that method; this strikes me a a bit rarer, but it most assuredly does happen).

    These are fairly trivial differences, of course. The real difference between these two approaches is that of readability; in my experience, x + "" is not very idiomatic in .NET and so I would be inclined to avoid it. That said, it could just be that it isn't common in the slice of the .NET world I inhabit, while there could be plenty of .NET developers out there who do it.

    I will point out that while in Java, perhaps you had to write the unwieldy Integer.toString(x) for variables x of primitive types like int, in C# and in .NET in general all types (including so-called "primitive" ones) inherit from object and so have the method ToString (along with GetType and GetHashCode) available to them.

提交回复
热议问题