Question

I've gone through and beat my head against the wall for a while now searched on various phrases and keywords but I cannot find anything close to an answer so i'm hoping someone here can shed some light.

Now if i try and rebuild that manually using the static methods of the Expression base class I run into an interesting issue. (I have broken down each step into its own Expression for debugging purposes)

That based on the values of the generated Expression tree above recreate the same basic expression tree as above (at least with the same "Look")

Everything steps through fine until you get to this line

BinaryExpression InsertPlusSpace = Expression.Add(Insert,Space);

The compiler throws an
InvalidOperationException was
unhandled

The binary operator Add is not defined
for 'System.String' and
'System.String'

Now why is this?

Why when I let C# convert a Lambda into an Expression does it obviously use the Add NodeType, and the Types display show it is definitely using System.String yet when i try and do the same manually it will not let the code continue?

I'm curious why it seems at least with what i have been able to find so far that string concatenation in expression trees works only if are not trying to build an expression tree manually that adds constants and variables of type System.String.

Popular Answer

Check the documentation: the '+' operator is actually not defined in the String class. I guess the compiler just knows it means "concatenate the strings", and it transforms it into a call to Concat. So when you call Expression.Add, you need to specify the method that implements the operation (in that case the String.Concat method).

I decompiled the expression with Reflector, it gives the following result (reformatted):