string = string + int: What's behind the scenes?
Asked Answered
S

2

66

In C# you can implicitly concatenate a string and let's say, an integer:

string sth = "something" + 0;

My questions are:

  1. Why, by assuming the fact that you can implicitly concatenate a string and an int, C# disallows initializing strings like this:

    string sth = 0; // Error: Cannot convert source type 'int' to target type 'string'
    
  2. How C# casts 0 as string. Is it 0.ToString() or (string)0 or something else?

  3. How to find an answer of the previous question?
Subminiaturize answered 3/8, 2010 at 16:32 Comment(1)
I particularly like how you ask "How to find an answer of the previous question?"Lathrop
K
71

It compiles to a call to String.Concat(object, object), like this:

string sth = String.Concat("something", 0);

(Note that this particular line will actually be optimized away by the compiler)

This method is defined as follows: (Taken from the .Net Reference Source)

    public static String Concat(Object arg0, Object arg1) {
        if (arg0==null) {
            arg0 = String.Empty; 
        }

        if (arg1==null) { 
            arg1 = String.Empty;
        } 
        return Concat(arg0.ToString(), arg1.ToString());
    }

(This calls String.Concat(string, string))


To discover this, you can use ildasm, or Reflector (in IL or in C# with no optimizations) to see what the + line compiles to.

Kylstra answered 3/8, 2010 at 16:34 Comment(4)
SLaks is correct, but to expound on the OP's questions: 1) "+" is an overloaded operator between string and object 2) Yes, .ToString() is ultimately called 3) ReflectorGentilis
See also this answer.Kylstra
It may be useful to throw up some IL to save a bit of time for those lazy programmers... (All of us...)Proustite
It seems that the compiler doesn't optimize this away; there's an interesting debate about this on JetBrains: devnet.jetbrains.com/thread/266160Callen
N
24

This is specified in section 7.8.4 of the C# 4 spec:

For an operation of the form x + y, binary operator overload resolution (§7.3.4) is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined addition operators are listed below. For numeric and enumeration types, the predefined addition operators compute the sum of the two operands. When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

The last sentence is the most relevant one to this situation.

Then later:

String concatenation

string operator +(string x, string y);

string operator +(string x, object y);

string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. 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.

That specifies how the integer is converted into a string.

And the result:

The result of the string concatenation operator is a string that consists of the characters of the left operand followed by the characters of the right operand. The string concatenation operator never returns a null value.

The actual means of performing concatenation is implementation-specific, but as noted in other answers, the MS implementation uses string.Concat.

Nalepka answered 3/8, 2010 at 16:36 Comment(5)
Does "abc" + 123 result in the 123 being boxed? Would "abc" + 123.ToString() be minimally more efficient?Cheekbone
@andleer: It's implementation-specific, but yes, it does... so in theory, 123.ToString() would be more efficient, but it's possible that the JIT is aware of this pattern.Nalepka
Crude benchmark with 25 million iterations shows ToString() to be about 7% quicker. Framework 4.5.1 and like I said, crude (but measurable).Cheekbone
has this feature been introduced in c# 4 ? I mean was it not there in prior versions of c# ?Wharfinger
@Dhanajay: What, the string conversion of non strings for concatenation? No, it's been there forever.Nalepka

© 2022 - 2024 — McMap. All rights reserved.