1

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

5
  • just Console.WriteLine("000"+"111"); Commented Mar 15, 2019 at 12:38
  • LINQPad is your friend. If you decompile something like var a = "1111"; var b = "222"; var c = a + b;, you'll see this ends up as a call to String.Concat. Commented Mar 15, 2019 at 12:39
  • @JeroenMostert is there a way to use LinqPad to generate code like in canton7 answer? I can find only IL code Commented Mar 15, 2019 at 12:54
  • @AleksAndreev SharpLab is good at showing the underling C#, but in this case it will show +. You'll need to go down to the IL to see what's happening (you can see call string [mscorlib]System.String::Concat(string, string)): sharplab.io/… Commented Mar 15, 2019 at 12:59
  • @AleksAndreev: not that I know of. LINQPad can dump expression trees ((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... Commented Mar 15, 2019 at 13:09

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.