[Mono-list] properties with indexers.

Jonathan Gilbert 2a5gjx302@sneakemail.com
Sat, 26 Jul 2003 00:19:26


At 10:27 AM 25/07/2003 -0400, you wrote:
>On Fri, 2003-07-25 at 10:17, Yves Kurz wrote:
>> Hallo..
>> 
>> maybe anyone of you can help me with this. Is it possible to write
>> properties which uses indexers? 
>> 
>Hello Yves,
>
>I see you are already hacking ;-).
>
>C# does not support this syntax. It only supports having such a syntax
>on the class itself.
>
>The best way to support the syntax is to do the following:
>
>public object [] O {
>	get {return o;}
>}
>
>That will allow the same syntax as you want. You can also return a
>collection, there are many examples of this in System.Web, especially in
>HttpRequest.

If you want to support that syntax, but still control assignment, then you
need to make an auxiliary class to handle the indexing:

class Container
{
  private int[] array;

  public readonly ArrayIndexer Array;

  public Container()
  {
    Array = new ArrayIndexer(this);
  }

  public class ArrayIndexer
  {
    public readonly Container Container;

    public ArrayIndexer(Container container)
    {
      Container = container;
    }

    public int this[int index]
    {
      get
      {
        return container.array[index];
      }
      set
      {
        if ((value % 2) != 0)
          throw new InvalidArgumentException("The value must be divisible
by 2", "value");
        container.array[index] = value;
      }
    }
  }
}

There are obviously a number of approaches you could take to giving the
auxiliary class access to the array. Probably the most efficient would be
to simply pass it a reference to the array itself; the approach shown above
has to get the field value from the Container instance on every access.
Depending on what you're doing, you may also be able to make multi-use
indexers.

What it comes down to, though, is that the C# language should simply
support parameters to any property (.NET supports it). I don't know why it
doesn't.

Anyway, best of luck with your C# hacking :-)

Regards,

Jonathan