views:

343

answers:

2

Consider the following code:

abstract class SomeClassX<T>
{
  // blah
}

class SomeClassY: SomeClassX<int>
{
  // blah
}

class SomeClassZ: SomeClassX<long>
{
  // blah
}

I want a collection of SomeClassX<T>'s, however, this isn't possible since SomeClassX<int> != SomeClassX<long> and List<SomeClassX<>> isn't allowed.

So my solution is to have SomeClassX<T> implement an interface and define my collection as, where ISomeClassX is the interface:

class CollectionOfSomeClassX: List<ISomeClassX>
{
  // blah
}

Is this the best way to do this, or is there better way?

+1  A: 

I would either use the interface you suggested, or make SomeClassX inherit from another class. It really depends on what you need to do with the objects in your collection. Whatever functionality they are going to have in common should go in a base class, or interface if that seems more appropriate.

Jon B
+1  A: 

Your best option is as you've suggested, create an interface ISomeClass and implement it. I recently tackled this same exact problem with a user preferences and profile system that we wanted to use to store a variety of data types. It came down to:

public interface IEntry
{
    // ...
    object Value { get; set; }
}

Specific Entry<Single> could be instantiated since Entry<T> implicitly implemented the interface:

public class Entry<T> : IEntry
{
    T Value { get; set; }
    object IEntry.Value { get { return Value; } set { return Value; } }
}

But when it came to IDictionary<string,IEntry> time we're back to casting the IEntry instances to the Entry<T> appropriate type or the Value property of IEntry to the appropriate type.

// assume entries is IDictionary<string,IEntry>...
var entry = entries["pizza-weight"];
var weight = (float)entry.Value;

This, of course, all makes sense because just as SomeClass<int> != SomeClass<long> so is true IList<SomeClass<int>> != IList<SomeClass<long>>.

cfeduke
I had thought of this, but discarded the idea, as casting is required when items are accessed. May as well use the old System.Collections :-)
VirtualStaticVoid