1

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.

Community
  • 1
  • 1
Tobiq
  • 2,489
  • 19
  • 38
  • Possible duplicate of [How do I overload the \[\] operator in C#](http://stackoverflow.com/questions/424669/how-do-i-overload-the-operator-in-c-sharp) – Alexis Côté Apr 19 '17 at 02:18

1 Answers1

1
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; }
   }
}
ErikE
  • 48,881
  • 23
  • 151
  • 196
  • Do you think this is simpler? http://stackoverflow.com/a/424677/7759514 – Tobiq Apr 19 '17 at 02:24
  • It depends on what you're trying to do. What are you trying to do? – ErikE Apr 19 '17 at 02:25
  • Call a function when values are set/get. I think I'll try the get/setValue functions first – Tobiq Apr 19 '17 at 02:26
  • Um, you can run whatever you want inside the set/get code I put above. How is that not brain-dead simple? – ErikE Apr 19 '17 at 02:27
  • What I was getting at was it's possible over-complication. It's only about 4 lines, though. – Tobiq Apr 19 '17 at 02:29
  • Nevermind.... For some reason I thought the Set/GetValue functions the answer-poster included were generic methods for array modification; seems not--the OP had defined them. Your post is the *actual* answer. – Tobiq Apr 19 '17 at 02:32