Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I started with your code (more or less) and resharper immediately told me that the cast to T was unnecessary:</p> <pre><code>public class Test { 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 { return new TournamentGame&lt;T, Y&gt;(gameId, new TournamentTeam&lt;Y&gt;(seed1, teams[seed1 - 1]), new TournamentTeam&lt;Y&gt;(seed2, teams[seed2 - 1])); } } internal class Team { } internal class TournamentTeam&lt;T&gt; { public TournamentTeam(int seed1, Team team) { throw new NotImplementedException(); } } internal class TournamentGame&lt;T, Y&gt; { public TournamentGame(int gameId, TournamentTeam&lt;Y&gt; tournamentTeam, TournamentTeam&lt;Y&gt; tournamentTeam1) { throw new NotImplementedException(); } } </code></pre> <p>So the need for the cast to T is coming from somewhere else. If you want a specific type of "constructor" for T, you can always pass along a factory method:</p> <pre><code> static TournamentGame&lt;T, Y&gt; make16Game&lt;T, Y&gt;(int gameId, int seed1, int seed2, Func&lt;int, Y, T&gt; tournamentTeamFactory, List&lt;Y&gt; teams) where T : TournamentTeam&lt;Y&gt; where Y : Team { return new TournamentGame&lt;T, Y&gt;(gameId, tournamentTeamFactory(seed1, teams[seed1 - 1]), tournamentTeamFactory(seed2, teams[seed2 - 1])); } </code></pre> <p>EDIT: Given the constructor code that you are using, it is clear why you need a cast to T (and why passing along a factory method, as I suggest above, is a good idea). If you want to limit TournamentGame to only taking TournamentTeams (which your code is <em>effectively</em> doing) then provide a constructor that takes TournamentTeam directly. If not, then you shouldn't be creating TournamentTeams in your make16Game function. Imagine the following:</p> <pre><code>public class AllStarTeam&lt;T&gt; : TournamentTeam&lt;T&gt; where T : Team { public AllStarTeam(int seed1, Team team) : base(seed1, team) { throw new NotImplementedException(); } } </code></pre> <p>Then this compiles, but throws a run time exception (a Bad Thing):</p> <pre><code>Test.make16Game&lt;AllStarTeam&lt;T&gt;, T&gt;(5, 5, 5, new List&lt;T&gt;()); </code></pre>
 

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