How can I simulate string + string expression via c# expression. The Expression.Add method does not work.
string + string expression like
"111" + "222" = "111222"
thanks
You need to call into string.Concat (the C# compiler turns string concatenation into calls to string.Concat under the hood).
var concatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
var first = Expression.Constant("a");
var second = Expression.Constant("b");
var concat = Expression.Call(concatMethod, first, second);
var lambda = Expression.Lambda<Func<string>>(concat).Compile();
Console.WriteLine(lambda()); // "ab"
Actually, if you write
Expression<Func<string, string string>> x = (a, b) => a + b;
and inspect it in the debugger, you'll see that it generates a BinaryExpression (with a Method of string.Concat(string, string)), not a MethodCallExpression. Therefore the compiler actually uses @kalimag's answer, and not mine. Both will work, however.
Expression.Add has an overload that takes a MethodInfo, which can be any static method that is compatible with the given parameter types:
var concatMethod = typeof(string).GetMethod(nameof(String.Concat), new [] { typeof(string), typeof(string)});
var expr = Expression.Add(Expression.Constant("a"), Expression.Constant("b"), concatMethod);
In practice this is similar to Expression.Call, but it produces a different expression tree and is displayed differently in the debugger.
Console.WriteLine("000"+"111");var a = "1111"; var b = "222"; var c = a + b;, you'll see this ends up as a call toString.Concat.+. You'll need to go down to the IL to see what's happening (you can seecall string [mscorlib]System.String::Concat(string, string)): sharplab.io/…(from _ in (new[] {""}).AsQueryable() let a = "111" let b = "222" select a + b).Expression) but this will print the actual expression (which really is.Add), so no good there. Then again, I don't mind reading IL...