I recently saw an example where the following was demonstrated:
T Add<T>(dynamic a, dynamic b) { return a + b; } Add<string>("hello", "world");
However, if I tried to use expressions to create a βcommonβ add function:
ParameterExpression left = Expression.Parameter(typeof(T), "left"); ParameterExpression right = Expression.Parameter(typeof(T), "right"); var add = Expression.Lambda<Func<T, T, T>>(Expression.Add(left, right), left, right).Compile(); // Fails with System.InvalidOperationException : The binary operator Add is not defined for the types 'System.String' and 'System.String' when T == String.
and then used this function with strings, it fails because the String type does not actually implement the + operator, but just the syntactic sugar for String.Concat ().
How then can the dynamics work? I figured that at runtime it goes through the point where + will be rewritten using String.Concat ().
source share