I\'m tracing legacy code in my project written in C#.
I find the following code:
public class FooCollection : Collection {};
I don't understand why (and when) we need to create our own Collection class like this.
One of the main use cases for implementing a custom Collection
is serialization.
If you want to customize how the collection is serialized (for example to XML, using XmlSerializable), you can create a custom collection class and implement IXmlSerializable
on it. Then, you can change how to read or write the collection by manipulating the Read
and Write
methods of that interface.
class MyCollection : Collection, IXmlSerializable
{
public XmlSchema GetSchema()
{
return(null);
}
public void WriteXml(XmlWriter writer)
{
//// foreach (var item in Items)
//// writer.Write...
}
public void ReadXml(XmlReader reader)
{
//// Items.Add(reader.Read...
}
}
This is in most cases preferable compared to implementing IXmlSerializable
on the parent class, as it leads to less code overall and promotes reuse (you can reuse the same collection in multiple places and it will be serialized in the same way as long as you use a XmlSerializer
to serialize it).
I've used this recently due to a requirement from an external system that needed each element of the collection to generate a XML node with the index of the element appended to it.
The final structure looked somewhat like this:
first item
second item
...
I'm not fond of coupling the collection to the serialization like this, but sometimes it is a valid approach.