The simplest thing to do is just specify the element type only and hard-code ICollection<T>
wherever you need it, e.g.
class MyClass<T> {
private ICollection<T> _items;
public MyClass(ICollection<T> items) {
_items = items;
}
public void Store(T obj) {
_items.Add(obj);
}
public ICollection<T> Items {
get {
return _items;
}
}
}
I recommend that you pass in a collection instance to the constructor rather than create one internally. It makes the class simpler and more "generic" (excuse the pun), and allows you to construct collection instances with non-default constructors, e.g. a dictionary with a non-default comparator.
RE-EDIT (3rd attempt): Using class inheritance and namespace aliasing to simulate typedef
are both OK up to a point, but both abstractions break down under certain circumstances. This code is the simplest I have found that actually compiles.
Step 1 - Define these classes:
// This KeyValuePair was being used to simulate a tuple. We don't need to simulate a tuple when we have a concrete class.
class BazAndListOfWrgl {
Baz Baz { get; set; }
List<Wrgl> Wrgls { get; set; }
}
// Simple typedef.
class BazAndListOfWrglDictionary : Dictionary<Bar, BazAndListOfWrgl> { }
Step 2 - Define these namespace aliases. All identifiers must be fully qualified. All types referenced must already be defined in a different physical file (since namespace aliases have to come before all code in a file).
using OuterDictionary = System.Collections.Generic.Dictionary<MyNamespace.Foo, MyNamespace.BazAndListOfWrglDictionary>;
using OuterDictionaryItem = System.Collections.Generic.KeyValuePair<MyNamespace.Foo, MyNamespace.BazAndListOfWrglDictionary>;
Step 3 - Use them like this:
class Program {
static void Main() {
// List-based example.
var listWrapper = new MyClass<BazAndListOfWrgl>(new List<BazAndListOfWrgl>());
listWrapper.Store(new BazAndListOfWrgl());
Console.WriteLine(listWrapper.Items.Count);
// Dictionary-based example.
var dictionaryWrapper = new MyClass<OuterDictionaryItem>(new OuterDictionary());
dictionaryWrapper.Store(new OuterDictionaryItem(new Foo(), new BazAndListOfWrglDictionary()));
Console.WriteLine(dictionaryWrapper.Items.Count);
}
}
The reasoning being: BazAndListOfWrglDictionary
cannot be a namespace alias because namespace aliases cannot depend on each other. OuterDictionary
and OuterDictionaryItem
cannot be derived classes because otherwise the compiler does not recognise one as being the element of the other.