Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I send 3 parameter to a function. (int d1, int d2, string operator)
For example : (12, 14, “>”).
Now in function I wants to have a condition.
Condition :
if (d1 operator d2) // is incorrect
if (d1 + operator + d2) // is incorrect
if (convert.toBolean (d1+ operator + d2)) // is incorrect
How can I write condition ?

Thanks very much
Posted

1 solution

Operator denoted by a character? Well, well…

This sounds like a really bad approach. By some reason, one worst misconception haunts the beginners: an attempt to use strings representing data, instead of data itself. And in this case, you are trying to use string instead of code. Is it even worse? I don't know, anyway, very bad…

Do you at least understand: should you misspell the "operator" character, the compiler won't warn you on the bug?

You can use a very simple and productive approach instead. Instead of "operator" (which is actually not, in your case), pass a delegate instance implementing the operator.

Are you getting the idea? Let's see:
C#
static bool MyMethod(int left, int right, System.Func<int, int, bool> userPredicate) {
    // ...
    bool result = userPredicate(left, right);
    // ...
    return result;
} // MyMethod


Now, how to use it in the call? Let's see:
C#
static void Test() {
     bool greater = MyMethod(2, 1, (l, r) => l > r);
     bool equal = MyMethod(4, 4, (l, r) => l == r);
} // Test


Simple enough, isn't it?

—SA
 
Share this answer
 
v9

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900