1

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;
    }
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
Toto
  • 7,491
  • 18
  • 50
  • 72
  • `ConstantExpression` isn't sealed, so it's possible for someone to override `NodeType` and return something else. Per the documentation for NodeType, "Extension nodes should return ExpressionType.Extension when overriding this method." – vcsjones Jul 15 '13 at 16:30
  • @vcsjones But its only constructor is `internal`, so that overriding is limited to mscorlib. – svick Jul 16 '13 at 10:15
  • @svick Oh good point, I didn't notice that. – vcsjones Jul 16 '13 at 13:31

2 Answers2

1

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.

cost
  • 4,420
  • 8
  • 48
  • 80
  • `ConstantExpression` is a class, so yeah, it can be `null`. But another question is: if you pass in invalid data (`null`), isn't it better to throw an exception? – svick Jul 16 '13 at 10:10
  • @svick It probably depends on what you're doing with the code. If you're doing something where the value could be null (no specific example comes to mind) and you need to do different things depending on if it's null or not. When I deal with datetime objects (not in these cases, just in general) I generally set them to null if they aren't assigned, instead of using the default `MinValue`. It's a personal preference, but it makes this sort of thing important to me. – cost Jul 16 '13 at 14:54
0

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

CSJ
  • 3,641
  • 2
  • 19
  • 29
  • Why do you imagine that? Type checking in the CLR is dirt cheap. It's a simple `Isinst` instruction. Properties do all sorts of interesting things, calling members, which require JITing if it isn't done yet, etc. – vcsjones Jul 15 '13 at 16:35
  • @Vcsjones, interesting ! Do you have link for more in depth explanation ? – Toto Jul 16 '13 at 08:33
  • That's awfully unspecific. In what way is it better? Why would you imagine that? – svick Jul 16 '13 at 10:12