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?
Func<int, string>
is a delegate that could be the address of a function or inline as lambda expression [ () => x
] .
Expression<TDelegate>
inherits from LambdaExpression and the NodeType
of an Expression<TDelegate>
is always ExpressionType.Lambda.
So, I think that kind of defensive code is not needed.