views:

64

answers:

1

I'm writing code that evaluates .NET Expression trees. I'm trying to create a C# 4 test to exercise my handling of an ExpressionType.Index, but I can't figure out how to create that type of expression through a LambdaExpression. No matter what I try, the expression comes out as an ExpressionType.Call or ExpressionType.ArrayIndex. For example:

IList<int> myList = new ObservableCollection<int> { 3, 56, 8 };
Expression<Func<int>> myExpression = () => myList[3]; 
// myExpression.Body.NodeType == ExpressionType.Call

myList = new int[] { 3, 56, 8 };
myExpression = () => myList[3]; 
// myExpression.Body.NodeType == ExpressionType.Call

int[] myArray = new int[] { 3, 56, 8 };
myExpression = () => myArray[3]; 
// myExpression.Body.NodeType == ExpressionType.ArrayIndex

List<int> myNonInterfaceList = new List<int> { 3, 7, 4, 2 };
myExpression = () => myNonInterfaceList[3]; 
// myExpression.Body.NodeType == ExpressionType.Call

What is an IndexExpression, and can one be created through an inline LambdaExpression in C# 4?

+1  A: 

An IndexExpression is exactly what you expect (i.e., array access or indexer property). It's one of the many new expression types that was ported over from the DLR. The C# 4.0 compiler, however, uses the same expression types as its previous version, so it won't use IndexExpression anywhere. Other languages may do so if their designers wish it.

To create an IndexExpression programmatically, use the static ArrayAccess(),MakeIndex(), or Property() methods on the Expression class.

Mark Cidade
Thanks for the answer. Where did you find that information? If there are some good articles out there that can shed some additional light on expression trees, I'd like to read those articles.
Jacob