I usually perform guard checking like so:
public void doStuff(Foo bar, Expression<Func<int, string>> pred) {
if (bar == null) throw new ArgumentNullException();
if (pred == null) throw new ArgumentNullException();
// etc...
}
I've seen this extra check which ensures that the predicate is actually a lambda:
if (pred.NodeType != ExpressionType.Lambda) throw new ArgumentException();
The ExpressionType
enum has many possibilities, but I don't understand how any of them would apply because I assumed the compiler would only allow a lambda.
Q1: Is there benefit to this? We do thorough guard checking of all inputs, so does this add value?
Q2: Is there a performance penalty - i.e. does it take longer than a regular type/bounds/null check?
Expression<<Func<int, string>>
describes a delegate that accepts an integer and returns a string, but does not actually define an instance of this delegate. This way you can create entire expression tree's by chaining them together. Checkout the mdsn article about the Expression class. – IcianExpression<Func<int, string>>
,pred
will always beExpression.Lambda
. I probably made this confusing because I thought for a while you were talking about theExpression
class in general. – Ician