probably a no-brainer, but please take a look at the following classes / Interfaces:
public interface IChallenge
public interface IChallengeView<T> where T : IChallenge
{
T Challenge {get;set;}
}
public interface IChallengeHostView
{
IChallengeView<IChallenge> ChallengeView { get; set; }
}
public class AdditionChallenge : IChallenge {}
public class AdditionChallengeView: IChallengeView<AdditionChallenge> {}
The scenario is a didactic app for young children.
I intend to keep the application flexible by separating the host (which could be any graphical surrounding) from the challenge that is to be solved. That way I could use the same surroundings to host addition, multiplication,division…
Now, when I want to fill this with some life, I get a conversion issue:
HostView hostView = new HostView(); // implements IChallengeHostView
AdditionChallengeView challengeView = new AdditionChallengeView();
hostView.ChallengeView = challengeView;
This, of course, does not work. I see why it doesn’t but I have no clue whatsoever how to get around this.
Any ideas?
UPDATE : I had decided to post as little code as possible before, but that brought me into the trouble of hiding one issue from you guys: The interface IChallengeView has a settable property (now visible in the code above), which makes covariance impossible to apply here – The generic type parameter can only be invariant in that case.
The answer given by rich.okelly is correct, but based on false assumptions (which, again, were based on the poor level of detail given by my description here).
I decided to make the code a little less implementation-type-adhesive, like so:
public interface IChallenge
public interface IChallengeView
{
IChallenge Challenge {get;set;}
}
public interface IChallengeHostView
{
IChallengeView ChallengeView { get; set; }
}
public class AdditionChallenge : IChallenge {}
public class AdditionChallengeView: IChallengeView {}
That means I have some more casting code in the AdditionChallengeView (and all other implementing classes), but it seems to me that this is the only viable way at the time.
If you’re using c#4 (or above) you can take advantage of variance. Try declaring your
IChallengeView<T>interface as covariant like so: