Andoni Zubizarreta
Andoni Zubizarreta

Reputation: 1335

Generate a C# expression that can concatenate two strings together

I'm trying to concatenate two strings together in a dynamic linq expression. The parameter I pass to the function must be a Dictionary<string, object>. The problem is that The Expression.Add throws me an error because it doesn't know how to add strings.

What I'm trying to achieve:

x => (string)x["FirstName"] + " Something here..."

What I have:

var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
var firstName = Expression.Call(pe, typeof(Dictionary<string, object>).GetMethod("get_Item"), Expression.Constant("FirstName"));
var prop = Expression.Convert(firstName, typeof(string));
var exp = Expression.Add(prop, Expression.Constant(" Something here..."))

Upvotes: 2

Views: 4603

Answers (1)

Jon Hanna
Jon Hanna

Reputation: 113262

Adding strings is neither one of the types that expressions handles explicitly (as it does for numeric primitives) nor going to work due to an overload of + (since string has no such overload), so you need to explicitly defined the method that should be called when overloading:

Expression.Add(
  prop,
  Expression.Constant(" Something here..."),
  typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))

This makes the overload of string.Concat that takes two string arguments the method used.

You could also use Expresssion.Call but this keeps your + intention explicit (and is what the C# compiler does when producing expressions, for that reason).

Upvotes: 8

Related Questions