Collection that inherits from ObservableCollection - What are the benefits?

c#

Solution

One major benefit is that you can define the `Add` function, which makes inline initialization easier. So for example this:

class MyCollection : ObservableCollection<MyObject> 
{  
    public void Add(string prop1, string prop2)
    {
        base.Add(new MyObject { Prop1 = prop1, Prop2 = prop2 });
    }
}

Lets you write this:

MyCollection collection = new MyCollection
{
    { "prop1", "prop2" },
    { "prop1", "prop2" },
};

A second (related) benefit: if you're working with XAML, having a subclassed collection lets you define collection instances (for design/test cases) as markup, as in:

<local:MyCollection xmlns:local="MyNamespace">
    <local:MyObject Prop1="prop1" Prop2="prop2" />
    <local:MyObject Prop1="prop1" Prop2="prop2" />
</local>

Lastly, (and this is merely a matter of taste, I suppose) it doesn't hurt in general, and can help. Sometimes you end up needing more methods/properties for a given collection type. It's nice to have a typed subclass ready, without needing to refactor.

Problem

After looking at this MSDN article, I am now wondering what the benefit, if any, is of defining a collection as a class that inherits from `ObservableCollection`. Are there any significant differences between this: ``` class MyCollection : ObservableCollection<MyObject> { } class Class1 { private MyCollection _newCollection = new MyCollection(); public Class1() { _newCollection.Add(new MyObject()); } } ``` and this: ``` class Class1 { private ObservableCollection<MyObject> _newCollection = new ObservableCollection<MyObject>(); public Class1() { _newCollection.Add(new MyObject()); } } ``` Is there something I'm overlooking here?

Original source