Some code to replicate the issue:
using System;
public abstract class Response { }
public abstract class Request<T> where T : Response { }
public class LoginResponse : Response { }
public class LoginRequest : Request<LoginResponse> { }
public class Program
{
static void Main(string[] args)
{
LoginRequest login = new LoginRequest();
/* Error: Cannot implicitly convert type 'LoginRequest' to 'Request' */
Request<Response> castTest = login;
/* No Error */
Request<LoginResponse> castTest2 = login;
}
}
As far as i can tell the LoginRequest class is a Request<Response> because is inherits from Request<T> and LoginResponse inherits from Response so can anybody enlighten me as to why i get the compiler error?
note: i have also tried an explicit cast
You’re getting the error because
Request<Response>andRequest<LoginResponse>are not covariant.Just because
LoginResponseinherits fromResponsedoesn’t mean thatRequest<LoginResponse>can be treated the same asRequest<Response>. Give this article a read:MSDN – Covariance and Contravariance in Generics