I need to write a generic class where the type parameter must be something implementing ICollection<T>. Inside of MyClass I need the collection’s item type (in the code snippet marked as ???).
class MyClass<TCollection> where TCollection : ICollection<???>
{
// ...
public void store(??? obj) { /* put obj into collection */ }
// ...
}
Often the collection will actually be a dictionary. Sometimes, it will be something simple as a list.
I know exactly how to do this in C++. How would I do this is C#?
The simplest thing to do is just specify the element type only and hard-code
ICollection<T>wherever you need it, e.g.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
typedefare 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:
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).
Step 3 – Use them like this:
The reasoning being:
BazAndListOfWrglDictionarycannot be a namespace alias because namespace aliases cannot depend on each other.OuterDictionaryandOuterDictionaryItemcannot be derived classes because otherwise the compiler does not recognise one as being the element of the other.