Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So I've got these classes that expose a collection of child objects.

I don't want other classes adding or removing objects from collections because I need to wire into events in the child objects, so as they get added or removed I want to be able to do additional processing. But I really love the ease of manipulating generics internally.

Did I mention this is a WPF app so I need INotifySupport?

The best I can come up with is something like this.

public class foo : INotifyPropertyChanged
{
    protected List<ChildFoo> _Children = new List<ChildFoo>();

    public foo()
    {
    }

    public void AddChild(ChildFoo newChild)
    {
        DoAttachLogic(newChild);
        _Children.Add(newChild);
        NotifyPropertyChange("Children");
    }

    public void RemoveChild(ChildFoo oldChild)
    {
        DoRemoveLogic(oldChild);
        _Children.Remove(oldChild);
        NotifyPropertyChange("Children");
    }

    public ChildFoo[] Children
    {
        get
        {
            return _Children.ToArray();
        }
    }

}

Are there serious flaws with this design that I'm not seeing?

Every time the Children property is accessed we get the overhead of converting list to an array.

Any advice on this would be great.

like image 249
Joel Barsotti Avatar asked Oct 08 '10 21:10

Joel Barsotti


1 Answers

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 Get
End Property

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

like image 129
Jonathan Allen Avatar answered Oct 06 '22 02:10

Jonathan Allen