10
public class Demo
{       
    public void When(Func<Person, bool> condition)
    {
        if (!condition)
        {
            Log.Info("Condition not met.");
            return;
        }

        // Do something
    }
}

In the When method, I would like to log when a predicate or Func<bool> returns false. However, just logging "condition not met" doesn't give me much information. If I call the method like so:

demo.When(x => x.Name == "John");

Is there a way to convert that expression into a readable/meaningful string for logging purposes?

nivlam
  • 3,223
  • 4
  • 30
  • 39
  • Agree with @Kirk Woll below. And assuming you don't want to change your method signature, you're likely SOL. See related: http://stackoverflow.com/questions/767733/converting-a-net-funct-to-a-net-expressionfunct. – David Peden Mar 29 '12 at 18:25

1 Answers1

14

There's not much useful meta data in an ordinary lambda. You could use expression trees instead:

void When(Expression<Func<Person, bool>> condition)
{
    var person = new Person();
    if (!condition.Compile()(person))
    {
        Console.WriteLine("Condition not met: " + condition);
        return;
    }
}

Then at the call site:

 When(x => false);

And the output will be:

Condition not met: x => False

However, expression trees introduce a lot more overhead, and condition.Compile is not cheap either. So I can't generally recommend this approach, but it will output useful info like you want.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195