I have a kind a simple question but I'm surprised.
This code works:
int itemID = 1;
string dirPath = @"C:\" + itemID + @"\abc";
Why don't I have to do itemID.ToString()
in this case ?
from MSDN
The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument 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.
Expanding on my answer a bit, based on some comments in other answers...
This process is not merely "Syntactic Sugar" or convenience. It is a result of a core C# language feature called Operator Overloading. In the case of the + Operator and the String + Overload, the Overload is provided as a means to abstract the internals of the String Class, which is a core fundamental of good design principles. The + String Overload provides type safety by ensuring that it never returns a null value, rather returning an empty string for any operand that cannot be converted using the .ToString()
method. However, even custom complex types (not just primitives) can be added to a string, assuming that they have a .ToString()
overload, without the implementation of the String type knowing any different.
Operator Overloading is a major language feature that more people should learn to harness the power of.
+
in string concatenation gets converted into string.Concat
call, which internally calls parameterless ToString
on each object.
string.Concate Method - MSDN
The method concatenates each object in args by calling the parameterless ToString method of that object; it does not add any delimiters.
EDIT:
Here is what it looks like in ILSpy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With