Search code examples
c#collectionstype-safety

What is the benefit of using type-safe collection classes?


I was wondering, why on some occasions i see a class representing some type's collection.

For example:

In Microsoft XNA Framework: TextureCollection, TouchCollection, etc. Also other classes in the .NET framework itself, ending with Collection.

Why is it designed this way? what are the benefits for doing it this way and not as a generic type collection, like was introduced in C# 2.0 ?

Thanks


Solution

  • The examples you gave are good ones. TextureCollection is sealed and has no public constructor, only an internal one. TouchCollection implements IList<TouchLocation>, similar to the way List<T> implements IList<T>. Generics at work here btw, the upvoted answer isn't correct.

    TextureCollection is intentionally crippled, it makes sure that you can never create an instance of it. Only secret knowledge about textures can fill this collection, a List<> wouldn't suffice since it cannot be initialized with that secret knowledge that makes the indexer work. Nor does the class need to be generic, it only knows about Texture class instances.

    The TouchCollection is similarly specialized. The Add() method throws a NotSupportedException. This cannot be done with a regular List<> class, its Add() method isn't virtual so cannot be overridden to throw the exception.

    This is not unusual.