1

I'm dynamically creating an expression tree using values provided in an XML file (i.e. I read strings). The value and the type of the member are read from this file. I'm trying to create a ConstantExpression of an integer:

XElement expression = GetMyCurrentMember();
//<member type="System.Int32">5</member>

return Expression.Constant(expression.Value, Type.GetType(expression.Attribute("type").Value, false, true));

In the return statement I'm getting the error Argument types do not match which, upon inspection, seams about right since I'm passing a string and saying it's an int. A simple cast would (probably) solve the problem but that means that I'm loosing the dynamic of the whole system. Instead of int I could have double or char or even a custom type and I don't really want to create a different call or method for every type. Is there a method to "force" the automatic conversion of the input value to the requested type?

Andrei V
  • 7,306
  • 6
  • 44
  • 64
  • If you "own" the XML format, you might consider using XAML instead of plain XML. That way you get strongly-typed values automatically. – Mike Strobel Feb 04 '14 at 15:37
  • @MikeStrobel unfortunatelly that's not an option. The expressions are going into a legacy file. – Andrei V Feb 04 '14 at 15:41

2 Answers2

3

You could "convert" the value, but you need to decide what to do if the conversion fails:

string value = expression.Value;
Type type = Type.GetType(expression.Attribute("type").Value, false, true);

return Expression.Constant(Convert.ChangeType(value, type), type);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

I think for a wide variety of types, a simple Convert.ChangeType will do the trick:

XElement expression = GetMyCurrentMember();
//<member type="System.Int32">5</member>
var formatProv = CultureInfo.InvariantCulture;
var type = Type.GetType(expression.Attribute("type").Value, false, true);
var value = Convert.ChangeType(expression.Value, type, formatProv);
return Expression.Constant(value, type);

Please note that by providing a format provider you can explicitly specify the culture you want to use in the conversion.

Markus
  • 20,838
  • 4
  • 31
  • 55