Passing in operators

  • Thread starter Thread starter Tem
  • Start date Start date
T

Tem

I have 3 static methods that share almost the same code with only a few
lines where different operators are used.

Is there a way to pass in an operator as a parameter?

pseudo code

Greater() {Base(>)}
Less() {Base(<)}
Equal() {Base(==)}

Base(operator op)
{
....

if(a op b)
....
}

Or another way of doing this?

Tem
 
Or another way of doing this?

Depending on what you are doing, you could use a delegate - i.e. a
Func<T,T,bool>; whether this is a good idea (or not) depends on the
scenario... easy enough in C# 3 with lambdas...

public static void Greater() {Base((x,y) => x > y);}
public static void Less() {Base((x,y) => x < y);}
public static void Equal() {Base((x,y) => x == y);}

private static void Base(Func<Foo,Foo,bool> op)
{
//...
if(op(a,b))
{
//...
}
}

(again: I stress hard to give a great answer without more info)

Marc
 
I should also add that for equaility (== said:
=) you can also use EqualityComparer<T>.Default and
Comparer<T>.Default to do a lot, without requiring direct access to
operators (actually it uses IComparable<T> and IEquatable<T>).

Marc
 
Can this be written with lambda expressions?

Paul E Collins said:
What you can do is pass in a delegate (method pointer) that performs the
desired comparison, e.g.


delegate bool CompareDelegate(int x, int y);


static void Main()
{
CompareDelegate lessThan = delegate(int x, int y) { return x < y; };
CompareDelegate moreThan = delegate(int x, int y) { return x > y; };

bool isLess = Compare(2, 5, lessThan); // true
bool isMore = Compare(2, 5, moreThan); // false
}


static bool Compare(int a, int b, CompareDelegate c)
{
return c(a, b);
}


Eq.
 
Can this be written with lambda expressions?

yes; I aleady posted a variant using lambdas (although using the
"delegate" version of a lambda*); using an actual Expression is
possible - not sure if it gains much, though (the delegate is likely
to be quicker than reflection from a PropertyInfo).

Whether this is the *best* approach depends largely on the full
scenario.

*=lambdas can be compiled to either a delegate or a System.Expression.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top