Toto
Toto

Reputation: 7719

Best way to determine if an expression is a constant expression

Which one do you prefer for testing if an expression is a ConstantExpression? From the NodeType property or a cast, and why?

    public static bool IsConstantExpression(Expression expression)
    {
        return expression.NodeType == ExpressionType.Constant;
        return expression is ConstantExpression;
    }

Upvotes: 1

Views: 146

Answers (2)

CSJ
CSJ

Reputation: 3951

I imagine that doing a property access is better than getting the runtime to check an object's type.

Upvotes: 0

cost
cost

Reputation: 4480

One difference is expression.NodeType == ExpressionType.Constant will throw an exception if expression is null. I'm pretty sure ConstantExpression is nullable, so that statement would be valid still.

Upvotes: 1

Related Questions