Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert string to int in expression

I'm working on a small project that transforms a list of functions into c# code. For example: temp1.greaterThan(1); temp2.contains("a"); temp1, temp2 are expression variables in string type. The source code is:

var temp1 = Expression.Variable(typeof(string), "temp1");   

So I think I need to convert temp1 into an integer variable. I've tried following ways but none worked:

Expression greaterThan = Expression.GreaterThan(temp1, Expression.Constant(1));

It will throw exeption because temp1 is string and hence cannot compare with 1.

Expression.GreaterThan(Expression.Call(typeof(int).GetMethod("Parse"), temp1), Expression.Constant(1));

It throws "Ambiguous match found." exception

Expression.GreaterThan(Expression.Call(typeof(Convert).GetMethod("ToInt32"), temp1), Expression.Constant(1));

Same exception: Ambiguous match found.

Expression.GreaterThan(Expression.Convert(temp1,typeof(Int32)), Expression.Constant(1));

Exception: No coercion operator is defined between types 'System.String' and 'System.Int32'.

So I'm thinking i would need to have a convert method inside the Expression.GreaterThan method. Anyone has an idea? Many thanks.

like image 489
Tùng Trịnh Avatar asked Feb 09 '23 02:02

Tùng Trịnh


1 Answers

You should use int.Parse to parse a string instead of explicit conversion. Note that int.Parse has a few overloads, that's why you get an "Ambiguous match found" exception.

var temp1 = Expression.Variable(typeof(string), "temp1");

//use int.Parse(string) here
var parseMethod = typeof(int).GetMethod("Parse", new[] { typeof(string) }); 

var gt = Expression.GreaterThan(Expression.Call(parseMethod, temp1), Expression.Constant(1));
like image 158
Cheng Chen Avatar answered Feb 11 '23 03:02

Cheng Chen