Indexing arrays and collections in expressions

Flee supports loading values from arrays and collections on the expression owner. You simply use square brackets after the variable and specify an index (which can itself be another expression or variable). If the variable being indexed is an array, Flee will emit IL optimized for loading array elements. If the indexed variable is not an array, Flee will try to find a default indexer property and use it instead. If the variable being indexed is not an array and does not have a default indexer, Flee will throw an ExpressionCompileException.

Here is some code that demonstrates how to index array and collection variables on the expression owner. We start by defining an expression owner class with some array and collection members:

class ExpressionOwner
{
    public int[] MyArray;
    public List<int> MyList;

    public ExpressionOwner()
    {
        MyArray = new int[] { 10, 20, 30 };

        MyList = new List<int>();
        MyList.Add(100);
        MyList.Add(200);
    }
}


We can now access the indexable members in an expression:

ExpressionOwner owner = new ExpressionOwner();

ExpressionContext context = new ExpressionContext(owner);
// Define a variable that can be used as an index
context.Variables.Add("index", 0);

// Access an element in the array
IGenericExpression<int> e = context.CompileGeneric<int>("MyArray[1+1]");
int value = e.Evaluate();

// Access an element in the collection using a variable as the index
e = context.CompileGeneric<int>("MyList[index + 1]");

value = e.Evaluate();


You can also define variables that are arrays. Once defined, you index them in the same way as above.

ExpressionContext context = new ExpressionContext();

// Define an array variable
context.Variables.Add("array", new int[] { 1, 2, 3 });

IGenericExpression<int> e = context.CompileGeneric<int>("array[1+1]");
int value = e.Evaluate();

Last edited Nov 9, 2008 at 10:00 PM by ECiloci, version 10

Comments

No comments yet.