Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties exposing array elements in C#

I want to create a property in C# that sets or returns an individual member of an array. Currently, I have this:

private string[] myProperty;
public string MyProperty[int idx]
{
    get
    {
        if (myProperty == null)
            myProperty = new String[2];

        return myProperty[idx];
    }
    set
    {
        myProperty[idx] = value;
    }
}

However, I get the following compile error:

Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.

like image 412
Paul Michaels Avatar asked Aug 23 '10 12:08

Paul Michaels


2 Answers

How about this: write a class that does one thing and one thing only: provide random access to elements of some underlying indexed collection. Give this class a this indexer.

For properties that you want to provide random access to, simply return an instance of this indexer class.

Trivial implementation:

public class Indexer<T>
{
    private IList<T> _source;

    public Indexer(IList<T> source)
    {
        _source = source;
    }

    public T this[int index]
    {
        get { return _source[index]; }
        set { _source[index] = value; }
    }
}

public static class IndexHelper
{
    public static Indexer<T> GetIndexer<T>(this IList<T> indexedCollection)
    {
        // could cache this result for a performance improvement,
        // if appropriate
        return new Indexer<T>(indexedCollection);
    }
}

Refactoring into your code:

private string[] myProperty;
public Indexer<string> MyProperty
{
    get
    {
        return myProperty.GetIndexer();
    }
}

This will allow you to have as many indexed properties as you want, without needing to expose those properties with the IList<T> interface.

like image 78
Dan Tao Avatar answered Sep 26 '22 03:09

Dan Tao


You must use this as the property name for indexers.

like image 28
leppie Avatar answered Sep 23 '22 03:09

leppie