Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>"I've tried instantiating a Collection directly instead of a List and that doesn't seem to work."</p> </blockquote> <p>What error do you get? You can definitely create an instance of <code>Collection&lt;T&gt;</code> 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:</p> <pre><code>var values = new System.Collections.ObjectModel.Collection&lt;int&gt; { 1,2,3,4 }; </code></pre> <p>I noticed your sample code has a <code>GenericTickType</code> and a <code>TickType</code>. 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, <code>Collection&lt;GenericTickType&gt;</code> and <code>Collection&lt;TickType&gt;</code> are two different classes and one is not assignable to the other.</p> <p>Now, if <code>TickType</code> is <em>castable</em> to <code>GenericTickType</code> (and they probably are if they are both enums, and assuming they share the same numeric values), you still cannot cast <code>Collection&lt;TickType&gt;</code> to <code>Collection&lt;GenericTickType&gt;</code>. There's no contra/co-variance in C# for most classes yet (coming in C# 4). But you could cast <em>each</em> <code>TickType</code> by doing something like this:</p> <pre><code>List&lt;GenericTickType&gt; list = new List&lt;GenericTickType&gt; { (GenericTickType)TickType.Price }; list.Add((GenericTickType)TickType.Price); // add more... Collection&lt;GenericTickType&gt;genericTicks = new Collection&lt;GenericTickType&gt;(list); </code></pre> <p>If you already have a <code>List&lt;TickType&gt;</code> and have access to C# 3.0 and LINQ, you can do this:</p> <pre><code>List&lt;TickType&gt; ticks = new List&lt;TickType&gt; { TickType.Price }; list.Add(TickType.Price); // add more... List&lt;GenericTickType&gt; castedList = ticks.Cast&lt;GenericTickType&gt;().ToList(); Collection&lt;GenericTickType&gt;genericTicks = new Collection&lt;GenericTickType&gt;(castedList); </code></pre> <p>This uses the LINQ <code>Cast&lt;T&gt;()</code> and <code>ToList&lt;T&gt;()</code> extension methods to cast <em>each</em> <code>TickType</code> in the original list to <code>GenericTickType</code> and creating a new <code>List&lt;GenericTickType&gt;</code> which is used to instantiate the <code>Collecion&lt;GenericTickType&gt;</code>. (I avoided using <code>var</code> so you could see the types in each step).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload