Tobiq
Tobiq

Reputation: 2657

Get-Set accessors for array property, with index handled

I have this class property

public object[] array { get; set; }

I'm able to get and set the entire array, as well as alter the individual items within the array.

How can I also achieve this with manual get-setters?

None of the answers to these 3 posts:

How do define get and set for an array data member?

Array property syntax in C#

Get/Set Method for Array Properties

cover what I'm needing to do.

object[] array;
public object[] Array {
    get { return array; }
    set { array = value; }
}

would allow me to get and overwrite the entire array, but I wish to have indexal access.

Upvotes: 1

Views: 5083

Answers (1)

ErikE
ErikE

Reputation: 50272

public sealed class ArrayWrapper<T> {
   private readonly T[] _array;
   public ArrayWrapper(T[] array) {
      if (array == null) throw new ArgumentNullException(nameof(array));
      _array = array;
   }

   public T this[int i] {
      get { return _array[i]; }
      set { _array[i] = value; }
   }
}

Upvotes: 1

Related Questions