title: c# How do I create a runtime expression for accessing the array index of a class with overridden [] operator?
body: <p>First only a bit familiar with Expressions, so any additional information about what I am doing is appreciated.  I am attempting to use the Expression.ArrayAccess on a class that has its operator [] overloaded.  This however throws an exception about the class is not an array.  Understandable but how to I access the value with the [] operator for a class?</p>
  <p>Here is an example chunk of code I modified to show the error.</p>
  <pre><code>using System;
  using System.Collections;
  using System.Collections.Generic;
  using System.Linq;
  using System.Linq.Expressions;
  
  public class HelloWorld
  {
      public class A {
          
          List&lt;int&gt; _list = new List&lt;int&gt;();
          
          public A(){
              for(int i = 0;i &lt; 10; i++)
              _list.Add(i);
          }
          public int this[int index]{
              get { return _list[index];}
          }
      }
      public static void Main(string[] args)
      {
          
          // This parameter expression represents a variable that will hold the class A.
          ParameterExpression arrayExpr = Expression.Parameter(typeof(A), &quot;x&quot;);
          
          // This parameter expression represents an array index.
          ParameterExpression indexExpr = Expression.Parameter(typeof(int), &quot;Index&quot;);
          
                  // This expression represents an array access operation.
          // It can be used for assigning to, or reading from, an array element.
          Expression arrayAccessExpr = Expression.ArrayAccess(
              arrayExpr,
              indexExpr
          );
  
          Expression&lt;Func&lt;A, int, int&gt;&gt; lambdaExpr = Expression.Lambda&lt;Func&lt;A, int, int&gt;&gt;(
              arrayExpr,
              indexExpr
          );
          
          // Print out expressions.
          Console.WriteLine(&quot;Array Access Expression:&quot;);
          Console.WriteLine(arrayAccessExpr.ToString());
          
          Console.WriteLine(&quot;Lambda Expression:&quot;);
          Console.WriteLine(lambdaExpr.ToString());
          
          Console.WriteLine(&quot;The result of executing the lambda expression:&quot;);
          
          // The following statement first creates an expression tree,
          // then compiles it, and then executes it.
          // Parameters passed to the Invoke method are passed to the lambda expression.
          Console.WriteLine(lambdaExpr.Compile().Invoke(new A(), 2));
      }
      
      
      
  }
  </code></pre>
  <p>what I want is simply x =&gt; x[idx]  where x is an instance of class A.</p>
  <p>For additional reference I am modifying <a href="https://www.codeproject.com/Articles/1079028/Build-Lambda-Expressions-Dynamically" rel="nofollow noreferrer">Build-Lambda-Expressions-Dynamically</a></p>