views:

73

answers:

4

I have a method with two overloads, as follows:

bool Evaluate(Func<bool> condition)
{
    // Some logic

    return condition.Invoke();
}

bool Evaluate<T>(Func<T, bool> condition, T value)
{
    // Same logic as the first method overload

    return condition.Invoke(value);
}

Since both method overloads contain largely identical logic, I wish to chain them together, but I can't see how to do this. I imagine the first method overoad needs to construct a delegate that it passes to the second overload, but it's not clear what form this delegate should take.

Many thanks for your advice,

Tim

+1  A: 

Something like this:

bool Evaluate(Func<bool> condition)
{
    return Evaluate(p => condition.Invoke(), false);
}
Pieter
Oeps, forgot the false at the end. Philip Rieck's is just this, but the other way around :).
Pieter
+1  A: 

Your first overload cannot call the second unless you are going to "make up" a value to pass. Your second can easily call the first, though.

bool Evaluate<T>(Func<T, bool> condition, T value)
{
   return Evaluate( () => condition(value));
}
Philip Rieck
+6  A: 

Try this (you don't need to call Invoke):

bool Evaluate(Func<bool> condition) {
  // logic ...
  return condition();
}

bool Evaluate<T>(Func<T, bool> condition, T value) {
  return Evaluate(() => condition(value));
} 

Or maybe your logic is reusable, it might make sense to extract it in its own method:

bool Evaluate(Func<bool> condition) {
  Logic();
  return condition();
}

bool Evaluate<T>(Func<T, bool> condition, T value) {
  Logic();
  return condition(value);
}

void Logic() {
  // logic...
} 
Jordão
Ha! I just posted *exactly* the same answer. But you beat me to the punch so +1.
LukeH
Thanks to everyone for their quick and consise responses. In fact, all of these answers would have solved my problem but I can only choose one.
Tim Coulter
+1  A: 

The easiest way is to wrap the original no parameter delegate with one that accepts and ignores a single parameter.

bool Evaluate(Func<bool> condition) 
{ 
    return Evaluate( _ => condition(), 0); 
} 
JaredPar