Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int to string without explicit conversion?

Tags:

c#

tostring

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 ?

like image 305
Tony Avatar asked Sep 10 '13 15:09

Tony


2 Answers

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.

like image 187
Claies Avatar answered Oct 05 '22 03:10

Claies


+ 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 enter image description here

like image 41
Habib Avatar answered Oct 05 '22 03:10

Habib