Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Casting oddity
    primarykey
    data
    text
    <p>I'm playing around with generics in a weird circumstance and I've come across a weird situation whose "solution" I don't expect to work. Here's the offending code...</p> <pre><code>static TournamentGame&lt;T, Y&gt; make16Game&lt;T, Y&gt;(int gameId, int seed1, int seed2, List&lt;Y&gt; teams) where T : TournamentTeam&lt;Y&gt; where Y : Team { /* * bunch of code removed for clarity */ // return that bad boy return new TournamentGame&lt;T, Y&gt;(gameId, (T)(new TournamentTeam&lt;Y&gt;(seed1, teams[seed1 - 1])), (T)(new TournamentTeam&lt;Y&gt;(seed2, teams[seed2 - 1]))); } </code></pre> <p>Looking at this, I don't see how the compiler allows this. My intuition is that I'll get a runtime error if I ever invoke this with a <code>T</code> other than <code>TournamentTeam</code>. If I don't put in the cast, I get a compile error. Is my intuition on this correct? What I'd LOVE to do is enforce a constraint that <code>T</code> must have a constructor that takes a <code>String</code> and a <code>Y</code> parameter, but that's another issue. I suppose I could also use reflection to get that constructor for <code>T</code>, but where's the fun in that?</p> <p>Anyway, thoughts?</p> <p>EDIT The <code>TournamentGame</code> looks like the following:</p> <pre><code>public class TournamentGame&lt;T, Y&gt; : Game&lt;T&gt; where T : TournamentTeam&lt;Y&gt; where Y : Team { public TournamentGame(int id, T t1, T t2, Region&lt;T, Y&gt; region = null) : base(id, t1, t2) { // do your thang } } public class Game&lt;T&gt; where T : Team { private T mTeam1 = null; private Game(int id) { // do your thang } public Game(int id, T t1, T t2) : this(id) { // do your thang } public T Team1 { get { // do your thang } } } </code></pre> <p>Sorry for leaving that out.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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