When trying to run the following code:
Expression<Func<string, string>> stringExpression = Expression.Lambda<Func<string, string>>(
Expression.Add(
stringParam,
Expression.Constant("A")
),
new List<ParameterExpression>() { stringParam }
);
string AB = stringExpression.Compile()("B");
I get the error referenced in the title: “The binary operator Add is not defined for the types ‘System.String’ and ‘System.String’.” Is that really the case? Obviously in C# it works. Is doing string s = "A" + "B" in C# special syntactic sugar that the expression compiler doesn’t have access to?
It’s absolutely right, yes. There is no such operator – the C# compiler converts
string + stringinto a call tostring.Concat. (This is important, because it means thatx + y + zcan be converted intostring.Concat(x, y, z)which avoids creating intermediate strings pointlessly.Have a look at the docs for string operators – only
==and!=are defined by the framework.