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?
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.
In the example that you give, there is no particular benefit. In general I think it is fair to say that you usually should avoid inheritance if you are not extending or overriding the inherited class in some way. That being said your sample is not quite faithful to the sample from the article.
public class NameList : ObservableCollection<PersonName>
{
public NameList() : base()
{
Add(new PersonName("Willa", "Cather"));
Add(new PersonName("Isak", "Dinesen"));
Add(new PersonName("Victor", "Hugo"));
Add(new PersonName("Jules", "Verne"));
}
...
In the MSDN sample, they have added additional logic in the classes constructor. In a real world example this class might have had a constructor that took a repository interface of some sort, or read from a file, or any number of things that are not part of the functionality of ObservableCollection So the answer to your original question is another question "Do you need to extend ObservableCollection< T >?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With