Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Adding Item to Collection [duplicate]

I'm sure there's an "easy" answer to this, but for the moment it escapes me.

In an MVVM application, I have a property that is a ObservableCollection, used for displaying some set of elements on the view.

private readonly ObservableCollection<MyType> mMyCollection = 
    new ObservableCollection<MyType>();
public ObservableCollection<MyType> MyCollection
{
    get { return mMyCollection; }
}

I want to restrict consumers of this collection from simply using the property to add to the collection (i.e. I want to prevent this from the view):

   viewModel.MyCollection.Add(newThing);   // want to prevent this!

Instead, I want to force the use of a method to add items, because there may be another thread using that collection, and I don't want to modify the collection while that thread is processing it.

public void AddToMyCollection(MyType newItem)
{
    // Do some thread/task stuff here
}
like image 401
Wonko the Sane Avatar asked Jan 01 '26 09:01

Wonko the Sane


2 Answers

Wrap your collection in a ReadOnlyCollection before giving it to the client, since you still have your non-readonly reference to it you can change it and they'll see the changes but they can't change it. See here for a sample.

like image 70
Hans Olsson Avatar answered Jan 03 '26 21:01

Hans Olsson


While it would require some work, the only way I can think to accomplish your goal is to create a new class, inherit from ObservableCollection<MyType> and hide the Add() method (via the new keyword).

You could even implement AddToMyCollection(MyType newItem) as:

public new void Add(MyType newItem)
{
    // Do some thread/task stuff here
    // And call base.Add() if you need
}

That way, the usage of your custom method is transparent.

If you didn't want anybody to be able to add items (through Add() or your custom method), you could simply return a ReadOnlyCollection which wouldn't allow anybody to add anything.

like image 39
Justin Niessner Avatar answered Jan 03 '26 23:01

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!