"I've tried instantiating a Collection directly instead of a List and that doesn't seem to work."
What error do you get? You can definitely create an instance of Collection<T>
directly, it is not an abstract class and it has several public constructors, including one that's parameter-less. You can do this, for example:
var values = new System.Collections.ObjectModel.Collection<int> { 1,2,3,4 };
I noticed your sample code has a GenericTickType
and a TickType
. Is this a mistake or do you actually have two classes? You said it's an enum (which one?), so one cannot possibly derive from the other. If they are two enum types, Collection<GenericTickType>
and Collection<TickType>
are two different classes and one is not assignable to the other.
Now, if TickType
is castable to GenericTickType
(and they probably are if they are both enums, and assuming they share the same numeric values), you still cannot cast Collection<TickType>
to Collection<GenericTickType>
. There's no contra/co-variance in C# for most classes yet (coming in C# 4). But you could cast each TickType
by doing something like this:
List<GenericTickType> list = new List<GenericTickType> { (GenericTickType)TickType.Price };
list.Add((GenericTickType)TickType.Price); // add more...
Collection<GenericTickType>genericTicks = new Collection<GenericTickType>(list);
If you already have a List<TickType>
and have access to C# 3.0 and LINQ, you can do this:
List<TickType> ticks = new List<TickType> { TickType.Price };
list.Add(TickType.Price); // add more...
List<GenericTickType> castedList = ticks.Cast<GenericTickType>().ToList();
Collection<GenericTickType>genericTicks = new Collection<GenericTickType>(castedList);
This uses the LINQ Cast<T>()
and ToList<T>()
extension methods to cast each TickType
in the original list to GenericTickType
and creating a new List<GenericTickType>
which is used to instantiate the Collecion<GenericTickType>
. (I avoided using var
so you could see the types in each step).