I’m using an API that has a method that requires this type of argument:
System.Collections.ObjectModel.Collection<GenericTickType> genericTickList
How do I instantiate an object for that argument? Here’s what I’ve tried but it keeps saying that the method call has some invalid arguments.
List<TickType> ticks_to_get = new List<TickType> { TickType.Price };
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:I noticed your sample code has a
GenericTickTypeand aTickType. 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>andCollection<TickType>are two different classes and one is not assignable to the other.Now, if
TickTypeis castable toGenericTickType(and they probably are if they are both enums, and assuming they share the same numeric values), you still cannot castCollection<TickType>toCollection<GenericTickType>. There’s no contra/co-variance in C# for most classes yet (coming in C# 4). But you could cast eachTickTypeby doing something like this:If you already have a
List<TickType>and have access to C# 3.0 and LINQ, you can do this:This uses the LINQ
Cast<T>()andToList<T>()extension methods to cast eachTickTypein the original list toGenericTickTypeand creating a newList<GenericTickType>which is used to instantiate theCollecion<GenericTickType>. (I avoided usingvarso you could see the types in each step).