title: Easy creation of properties that support indexing in C#
body: <p>In C# I find <a href="http://msdn.microsoft.com/en-us/library/aa288464(VS.71).aspx" rel="noreferrer">indexed properties</a> extremely useful. For example:</p>
  
  <pre><code>var myObj = new MyClass();
  myObj[42] = "hello"; 
  Console.WriteLine(myObj[42]);
  </code></pre>
  
  <p>However as far as I know there is no syntactic sugar to support fields that themselves support indexing (please  correct me if I am wrong). For example:  </p>
  
  <pre><code>var myObj = new MyClass();
  myObj.field[42] = "hello"; 
  Console.WriteLine(myObj.field[42]);
  </code></pre>
  
  <p>The reason I need this is that I am already using the index property on my class, but I have  <code>GetNumX()</code>, <code>GetX()</code>, and <code>SetX()</code> functions as follows: </p>
  
  <pre><code>public int NumTargetSlots {  
      get { return _Maker.NumRefs; }  
  }
  public ReferenceTarget GetTarget(int n) {
      return ReferenceTarget.Create(_Maker.GetReference(n));
  }
  public void SetTarget(int n, ReferenceTarget rt) {
      _Maker.ReplaceReference(n, rt._Target, true);
  }
  </code></pre>
  
  <p>As you can probably see exposing these as one indexable field property would make more sense. I could write a custom class to achieve this every time I want the syntactic sugar but all of the boilerplate code just seem unnecessary. </p>
  
  <p>So I wrote a custom class to encapsulate the boilerplate and to make it easy to create properties that can be indexed . This way I can add a new property as follows:</p>
  
  <pre><code>public IndexedProperty&lt;ReferenceTarget&gt; TargetArray  {
      get { 
         return new IndexedProperty&lt;int, ReferenceTarget&gt;(
             (int n) =&gt; GetTarget(n), 
             (int n, ReferenceTarget rt) =&gt; SetTarget(n, rt));
         }
  }
  </code></pre>
  
  <p>The code for this new IndexedProperty class looks like:</p>
  
  <pre><code>public class IndexedProperty&lt;IndexT, ValueT&gt;
  {
      Action&lt;IndexT, ValueT&gt; setAction;
      Func&lt;IndexT, ValueT&gt; getFunc;
  
      public IndexedProperty(Func&lt;IndexT, ValueT&gt; getFunc, Action&lt;IndexT, ValueT&gt; setAction)
      {
          this.getFunc = getFunc;
          this.setAction = setAction;
      }
  
      public ValueT this[IndexT i]
      {
          get {
              return getFunc(i);
          }
          set {
              setAction(i, value);
          }
      }
  }
  </code></pre>
  
  <p>So my question is: <strong>is there a better way to do all of this</strong>? </p>
  
  <p>Well to be specific, is there a more idiomatic way in C# to create an indexable field property, and if not how could I improve my <code>IndexedProperty</code> class? </p>
  
  <p><strong>EDIT:</strong> After further research, Jon Skeet calls this a "<a href="https://stackoverflow.com/questions/3293495/is-following-indexer-property-possible/3293558#3293558">named indexer</a>".</p>