Tim Coulter
Tim Coulter

Reputation: 8927

How to chain method overloads that accept Func<> delegates ? (C#)

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

Upvotes: 1

Views: 1279

Answers (4)

Philip Rieck
Philip Rieck

Reputation: 32568

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));
}

Upvotes: 1

JaredPar
JaredPar

Reputation: 754705

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); 
} 

Upvotes: 1

Jord&#227;o
Jord&#227;o

Reputation: 56467

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...
} 

Upvotes: 6

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

Something like this:

bool Evaluate(Func<bool> condition)
{
    return Evaluate(p => condition.Invoke(), false);
}

Upvotes: 1

Related Questions