0

i have a problem to create my code structure i don't now how to make it work

the problem in PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>(); where it connot be converted

here is the code sample

public class PlayListInfo<_VerseTrack> : IPlayListInfo
    where _VerseTrack : VerseTrack
{
     public List<_VerseTrack> Tracks;
}

public class VerseTrack1: VerseTrack
{

}

public class VerseTrack2: VerseTrack
{

}


public class player
{
    PlayListInfo<VerseTrack> ProgresList;
}

public class player1:player
{
   PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>();
}
public class player2:player
{
}
Hager Aly
  • 1,113
  • 9
  • 25

2 Answers2

4

Generic types aren't inherited based on their type parameters. A PlayListInfo<QuranVerseTrack> is not a PlayListInfo<VerseTrack>

You could do:

PlayListInfo<VerseTrack1> ProgresList = new PlayListInfo<VerseTrack1>();

and then treat all of the items like a VerseTrack, but it's unclear if that's what you should do.

or you could do:

PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack>();

and then add VerseTrack1 (or VerseTrack2) items to it (assuming it's a collection of some sort).

Side note: player1.ProgresList is hiding the base property, not overriding it.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Agreed, and the type constraint he already has is sufficient for the limitation he's trying to set. – Paul Dec 02 '14 at 16:45
1

If you are using .NET 4.0 or higher, here's another workaround. I introduce you covariance and contravariance

Assuming A is convertible(implicit reference conversion is available) to B, 
X is covariant if X<A> is convertible to X<B>

Since covariance and contravariance only work with interface, you need to modify IPlayListInfo like this:

public interface IPlayListInfo<out _VerseTrack> 
  where _VerseTrack : VerseTrack
{
  // blah blah ... 
}

And this might work!

public class player1:player
{
  // PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>(); // old one
  IPlayListInfo<VerseTrack> ProgressList = new PlayListInfo<VerseTrack1>() as IPlayListInfo<VerseTrack1>;
}
Joon Hong
  • 1,337
  • 15
  • 23