Is there a good pattern for exposing a generic collection as readonly? Is there a good pattern for exposing a generic collection as readonly? wpf wpf

Is there a good pattern for exposing a generic collection as readonly?


This is what I do for normal code:

Public Readonly Property Childern As ObjectModel.ReadOnlyCollection(Of Child)    Get       Return New ObjectModel.ReadOnlyCollection(Of Child)(_ChildernList)    End GetEnd Property

For WPF code I would just expose a subclass of ObservableCollection.


You should use ObservableCollection as field in your class, you then have full access to modify collection. Then expose this as ReadonlyObservableCollection via property.And if you dont change collection itself (eg. nochildren = new ObservableCollection(), you should make field readonly), then you dont need any kind of notifyPropertyChanged on this property, because it doesnt change and collection itself handles those events for its children.

public class Child{    public int Value { get; set; }}class MyClassWithReadonlyCollection{    private readonly ObservableCollection<Child> _children = new ObservableCollection<Child>();    public MyClassWithReadonlyCollection()    {        _children.Add(new Child());    }    //No need to NotifyPropertyChange, because property doesnt change and collection handles this internaly    public ReadOnlyObservableCollection<Child> Children { get { return new ReadOnlyObservableCollection<Child>(_children); } }}


I changed the "add child" and "remove child" to protected since you are saying you don't want other classes modifying your collection. I changed your List to ObservableCollection so you can recieve collection changed notifications. Since you are using an IList there is no need to call ToArray(), just access directly.

try this:

public class foo : INotifyPropertyChanged{    protected ObservableCollection<ChildFoo> _Children = new ObservableCollection<ChildFoo>();public foo()    {    }protected void AddChild(ChildFoo oldChild){    DoAttachLogic(newChild);    _Children.Add(newChild);    NotifyPropertyChange("Children");}protected void RemoveChild(ChildFoo oldChild){    DoRemoveLogic(oldChild);    _Children.Remove(oldChild);    NotifyPropertyChange("Children");}public ChildFoo this[int n]{    get    {        return _Children[n];    }}}