0

I'm trying to do this with Dictionary, Array seems more general so I'm using it as an example.

Class MyArray
{
    private Array array;

    public Array [p] // a property
    {
        get {return array[p]};
        set
        {
            array[p] = value;
            more_stuff();
        }
    }
}

This is sudo-code. I've included only a part of the class, where my problem would be. Can I use a property as above, or another structure to achieve this?

(new MyArray[]{4, 3, 1, 5})[2] = 4;
3
  • 1
    This doesn't even compile. What problem are you trying to solve? Commented Feb 5, 2014 at 11:02
  • Creating my own class, that in this case uses an array, with array like [ ] functionality/interface. See the name I chose for the class and what I seem to be trying to do above. I need more tasks to occur for each assignment to the array, as shown with more_stuff(). Commented Feb 5, 2014 at 11:07
  • I think you are looking for and indexer msdn.microsoft.com/en-us/library/6x16t2tx.aspx Commented Feb 5, 2014 at 11:11

1 Answer 1

4

You're looking for an indexer.

So you're class should look like this:

class MyArray<T>
{
    private T[] array = new T[100];

    public T this[int p]
    {
        get 
        {
            return array[p];
        }
        set
        {
            array[p] = value;
            // more_stuff();
        }
    }
}

To be able to use a collection initializer (e.g. new MyArray<int>{4, 3, 1, 5}), your class has to implement IEnumerable and provide a Add method.

Sign up to request clarification or add additional context in comments.

1 Comment

Super ت Intuitive too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.