";...">

Convert string value to C # statement

Im trying to figure out a way to create a conditional dynamically.

In the example

var greaterThan = ">"; var a = 1; var b = 2; if(a Convert.ToOperator(greaterThan) b) {...} 

I read this post but couldn't figure out how to implement some things. C # convert string to use in boolean state

Ano Consulting is highly appreciated

thanks

+8
operators c # conditional
source share
3 answers

I was not going to publish it, but thought it might help. Assuming, of course, that you don't need extended general logic in John's post.

 public static class Extension { public static Boolean Operator(this string logic, int x, int y) { switch (logic) { case ">": return x > y; case "<": return x < y; case "==": return x == y; default: throw new Exception("invalid logic"); } } } 

You can use such code, with greaterThan being a string with the required logic / operator.

 if (greaterThan.Operator(a, b)) 
+10
source share

You cannot do this. Closest you could come:

 Func<T, T, bool> ConvertToBinaryConditionOperator<T>(string op) 

and then:

 if (ConvertToBinaryConditionOperator<int>(input)(a, b)) { } 

The hard bit is what ConvertToBinaryConditionOperator will do. Maybe you should take a look at Mark Gravell working on introducing generic operators in MiscUtil . Expression trees can be really useful in this case, although I believe Marc has a working approach that also works on .NET 2.

So, in this case you might have something like (using MiscUtil )

 public static Func<T, T, bool> ConvertToBinaryConditionOperator<T>(string op) { switch (op) { case "<": return Operator.LessThan<T>; case ">": return Operator.GreaterThan<T>; case "==": return Operator.Equal<T>; case "<=": return Operator.LessThanOrEqual<T>; // etc default: throw new ArgumentException("op"); } } 
+11
source share

A more general way to do this is to take any IComparable objects.

  public static bool Compare<T>(string op, T left, T right) where T : IComparable<T> { switch (op) { case "<": return left.CompareTo(right) < 0; case ">": return left.CompareTo(right) > 0; case "<=": return left.CompareTo(right) <= 0; case ">=": return left.CompareTo(right) >= 0; case "==": return left.Equals(right); case "!=": return !left.Equals(right); default: throw new ArgumentException("Invalid comparison operator: {0}", op); } } 
+4
source share

All Articles