C. Ross
C. Ross

Reputation: 31848

How to design a inherited collection

I'm writing a program in C# that has a custom collection. The custom collection performs some useful aggregate functions (AllSuccessful, %Successful, etc) over it's members which are of type ResultInfo. I have several classes that derive from ResultInfo (UploadResultInfo, XUploadResultInfo, and YUploadResultInfo), and would like to have additional collections that inherit from ResultInfoCollection that have additional aggregate functions. The only problem with doing this as specified is that it leaves a useless

public void Add(ResultInfo item)
{ 

}

on the collection. Clarification: This method takes an argument of type ResultInfo, but a ResultInfo added to an UploadResultInfoCollection will throw an error. Is there an elegant way of solving my problem? I've considered generics but I don't quite know how that would work.

Upvotes: 0

Views: 297

Answers (4)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

If all you're doing is providing some extra methods to an otherwise existing collection type, then consider simply defining extension methods for that type and using a normal generic collection.

Upvotes: 0

ShuggyCoUk
ShuggyCoUk

Reputation: 36438

Consider whether your useful methods actually need to be instance methods.

Do they need to maintain state when other operations happen or are they all possible using the publically avaialable (or internaally available) API?

If so then simply make them static methods (extension methods is probably a good idea) and don't worry about inheritance. If the methods are meaningful on IEnumerable<T> then so much the better, by doing this you make your utility functions vastly more usable and thus useful.

Using the resulting package of functions simply requires importing the relevant namespace.

Upvotes: 0

user60229
user60229

Reputation:

To define a generic class that handles any child of ResultInfo you just define it like

public class MyCollection<T> : ICollection<T>
where T : ResultInfo
{

     ... the required methods ... just use "T" instead of "ResultInfo" ...

    public void Add(T item) {}
}

Later on you can use it by

 MyCollection<FooResultInfo> coll = new MyCollection<FooResultInfo>();

Just try using them, they are not too difficult and learning by doing is the best way ...

Upvotes: 2

foson
foson

Reputation: 10227

I'm not sure how you are left with a useless Add method.

If the collection populates itself, you can make the Add method private.

If you want your "inherited" additional collections to not expose the Add method, use composition instead of inheritance.

Upvotes: 0

Related Questions