In an Expression Tree, have you checked type-cast?

c# expression-trees

Question

I'm writing a little amount of dynamically generated code in Expression. With one exception, my approach works. I wish to do a verified type-cast, in which case a TypeCastException is raised.

I've discovered Expression. When a cast fails, TypeAs(), which performs the type conversion, returns null rather than issuing an exception.

Exists a straightforward method in Expression to do a checked type-cast? Or do I need to throw the exception myself after checking for null?

What I have is this:

ParameterExpression typedAttribute = Expression.Variable(attributeType, "typedAttribute");
ParameterExpression typedValue = Expression.Variable(valueType, "typedValue");

BlockExpression methodBlock = Expression.Block(new[] { typedAttribute, typedValue }, new Expression[]
   {
       Expression.Assign(typedAttribute, Expression.TypeAs(attribute, attributeType)),
       Expression.Assign(typedValue, Expression.TypeAs(value, valueType)),
       Expression.Call(visitor, methodInfo, typedAttribute, typedValue),
       Expression.Assign(visited, Expression.Constant(true)),
   });
1
11
6/27/2011 7:33:10 AM

Accepted Answer

Expression.Convert should serve as a cast in this.

14
6/27/2011 7:35:39 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow