Home > Enterprise >  How to call a method whenever an entry of an array-type property is changed?
How to call a method whenever an entry of an array-type property is changed?

Time:06-07

I have a property of type double[] with a public get and set accessor. I would like to call some input check whenever one element of the array is changed.

I have tried the following:

private double[] myArray;

public double[] MyArray
{
    get { return myArray; }
    set 
    {
        CheckInput(value);
        myArray = value;
    }
}

However, when I run for example classInstance.MyArray[3] = 5; the CheckInput method is not called (which makes sense, as the array is only modified but not re-set to a new object).

CodePudding user response:

Raw arrays cannot be intercepted. You can, however, add your own indexer instead of exposing the raw array:

private double[] myArray;

public double this[int index]
{
    get { return myArray[index]; }
    set 
    {
        // your per-element validation here, using 'value' and 'index'
        myArray[index] = value;
    }
}

The caller would then use yourObj[index] to talk to the indexer.

CodePudding user response:

Maybe create your own double[] class and overload the indexer:

static void Main(string[] args)
    {
        var extArray = new ExtendedArray<double>(10);
        extArray[0] = 2.5;
    }

    public class ExtendedArray<T>
    {
        private T[] _array;

        public ExtendedArray(int size)
        {
            _array = new T[size];
        }

        public T this[int index]
        {
            get => _array[index];
            set
            {
                _array[index] = value;
                // Do other stuff here
            }
        }
    }

CodePudding user response:

Considering you will know the index and value anytime you are trying to set the array, you could have a method that you call instead:


public void UpdateMyArray(int index, double value){

    MyArray[index] = value;
    // Do other things here

}

If that doesn't work for you, it's possible to create your own array type and have an indexer attached to your class, but it would probably be easier to implement an ObservableCollection.

  • Related