1

Is it possible to write an if statement with a changing operator?

The operator (<,>, =<; >=, =) has been saved earlier in a text file and is now a available in a string array called Parameter.

For example: Parameter [0] = {"<"};

The code should look like:

if (3 "Parameter[0]" 5) {//do something}

Thanks for helping!

Andy V.
  • 11
  • 3
  • Possible duplicate of [Evaluating string "3\*(4+2)" yield int 18](https://stackoverflow.com/questions/333737/evaluating-string-342-yield-int-18) – Alex K. Aug 24 '17 at 13:49

4 Answers4

3
Dictionary<string, Func<int, int, bool>> functions = ...;
functions.Add("<", (a,b) => a < b);
functions.Add(">", (a,b) => a > b);

Then to use it:

if(functions[Parameter[0]](3, 5)){...}
lancew
  • 780
  • 4
  • 22
2

Just for completeness to the other two answers, you can return a custom comparer function:

public Func<int, int, bool> CustomComparer(string parameter) {
    switch(parameter) {
        case(">="): return (a, b) => a >= b;
        case(">"): return (a, b) => a > b;
        //...
    }
}

and call it like this:

if(CustomComparer("<=")(3, 5)) { ... }

or:

var FirstIsGreater = CustomComparer(">");
if(FirstIsGreater(3, 5)) {... }
CookedCthulhu
  • 744
  • 5
  • 14
1

If really this is all you need. you can make a switch case:

switch(Operator){
  case '<': return a < b;
  case '>': return a > b;
  ...
}
Joel Harkes
  • 10,975
  • 3
  • 46
  • 65
0

This is called metaprogramming and is generally not available in C#. In general you would not be able to do this in any staticly-typed language (in the statically typed language that support metaprogramming, the "code string" must be known during compile time). What you can do is:

  1. Do as Joel said and just make a switch-case (though this can get ugly if extracting the operator's difficult).
  2. Create a dictionary that maps operators to functions, and create a function that extracts the operator from the source string (like lancew did).
  3. Programmatically write runnable C# code and compile it at runtime (for the love of god, don't actually do this just to compare two numbers).
bentheiii
  • 451
  • 3
  • 15