Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting problem in C# generic method
    text
    copied!<p>I'm having some trouble with a generic method I'm writing. It has the following signature;</p> <pre><code>public static ThingCollection&lt;T&gt; GetThings&lt;T&gt;(...) where T : Thing </code></pre> <p>There are several classes; ThingA, ThingB and ThingC that inherit from Thing; and I want to be able to have code something like this in the method.</p> <pre><code>var things = new ThingCollection&lt;T&gt;(); if (typeof(T) == typeof(Thing)) foreach (var item in someCollection) things.Add((T)new Thing(...)); else if (typeof(T) == typeof(ThingA)) foreach (var item in someCollection) things.Add((T)new ThingA(...)); else if (typeof(T) == typeof(ThingB)) foreach (var item in someCollection) things.Add((T)new ThingB(...)); else if (typeof(T) == typeof(ThingC)) foreach (var item in someCollection) things.Add((T)new ThingC(...)); else throw new Exception("Cannot return things of type " + typeof(T).ToString()); return things; </code></pre> <p>The problem is that I get a <em>best overloaded method match has invalid arguments</em> error if I don't cast the new objects. Adding the T casts as shown above is fine for the new Thing() but reports <em>Cannot convert type 'ThingA' to 'T'</em> for the other new calls. Intellisense indicates that T is a Thing but I don't understand why I can't cast the other objects to Thing, as they inherit from it.</p> <p>Perhaps this is not the right way to be doing what I'm trying to do. Am I on the right track? Perhaps missing some small nuance, or should I be doing something else entirely?</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