1

Consider the following code:

public ObservableCollection<Message> Messages {
   get { return new ObservableCollection<Message>(); }
}

Is there anything I can do to prevent the caller code from adding/removing/changing items?

EDIT: Sorry, everyone, I just noticed it's a dupe, but the accepted answer is wrong.

Community
  • 1
  • 1
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • possible duplicate of [How can I make a read-only ObservableCollection property?](http://stackoverflow.com/questions/1763696/how-can-i-make-a-read-only-observablecollection-property) – Søren Boisen Jun 03 '15 at 12:07
  • The accepted answer on the original question is now correct and better formulated than the accepted answer here. – Søren Boisen Jun 03 '15 at 12:08

4 Answers4

12

What about using ReadOnlyObservableCollection

Code would be:

public ReadOnlyObservableCollection<Message> Messages 
{
  get { return new ReadOnlyObservableCollection<Message>(new ObservableCollection<Message>()); }
}

Having read aboutReadOnlyObservableCollection Anti Pattern I realise the above is the not a good approach and may lead to subtle bugs. The suggested approach is:

public class MyClass
{
  public MyClass()
  {
    myCollection = new ObservableCollection<Message>();
    myReadOnlyCollection = new ReadOnlyObservableCollection<Message>(myCollection);
  }

  public ReadOnlyObservableCollection<Message> Messages 
  {
    get { return myReadOnlycollection; }
  }

  private readonly ObservableCollection<Message> myCollection;
  private readonly ReadOnlyObservableCollection<Message> myReadOnlyCollection;
}
IndigoDelta
  • 1,481
  • 9
  • 11
2

Why do you need a read only ObservableCollection. If this collection is read only you don't need to observe it. Consider a Collection<T>

Arturo Martinez
  • 3,737
  • 1
  • 22
  • 35
  • 2
    I'm thinking he *wants* to be able to modify it, but he doesn't want to let others do so. He *does* want them to be notified of changes that he made, however. –  Jun 14 '11 at 16:54
  • 1
    It is quite common to want to expose a *read-only view* for a collection and have the changes be observable to the outside. Often you want to make changes in response to events, but want to do it in a controlled fashion inside the class, not at the whim of outside code. – Søren Boisen Jun 03 '15 at 12:06
2

Return a ReadOnlyObservableCollection instead:

private ReadOnlyObservableCollection<Message> _Messages;

public ReadOnlyObservableCollection<Message> Messages {
   get { this._Messages = this._Messages ?? new ReadOnlyObservableCollection(new ObservableCollection<Message>()); return this._Messages; }
}
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
1

What about to use the ReadOnlyObservableCollection< T >