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?
There’s not much useful meta data in an ordinary lambda. You could use expression trees instead:
Then at the call site:
And the output will be:
However, expression trees introduce a lot more overhead, and
condition.Compileis not cheap either. So I can’t generally recommend this approach, but it will output useful info like you want.