Jaime Oro
Jaime Oro

Reputation: 10135

Array change event

I've an array property called Value:

public string[,] Value { get; set; }

I want to call the Save() method when any value of the array (not the entire array) has changed.

Is there an easy way to implement it?

Upvotes: 4

Views: 7920

Answers (3)

earlNameless
earlNameless

Reputation: 2918

Not really. Arrays are very primitive types and do not notify you when things change.

The best you can do is create a custom type that acts like a 2D array, but in addition it raises an event when an element has changed. Your current class would then subscribe to this event and call Save().

Some additional comments:

  • You probably do not want to expose the setter, this allows people to change which array you are pointing to. You probably want to expose only the getter, so they can change values, but not the whole array.
  • There might already be a type for what I mentioned, I do not know of one.
  • If you are going to change the APIs anyways, it might make more sense to expose an indexer on your class, then call Save() when the indexer's setter is called. See below.
    public string this[int x, int y] 
    { 
        get { return this.localArray[x,y]; }
        set 
        { 
            this.localArray[x,y] = value;
            this.Save();
        }
    }

Upvotes: 5

Hans Passant
Hans Passant

Reputation: 941615

Don't use an array. Think ObservableCollection<>, make your own if the one in the box doesn't fit your needs. And drop the setter, you don't want the client code to break your notifications.

Upvotes: 3

Vlad
Vlad

Reputation: 35594

Why not create an own indexer (like the one here, so that you know exactly when your "array" is updated? You can call Save from the setter.

Upvotes: 2

Related Questions