string = string + int: What’s behind the scenes?

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.

Leave a Comment