Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't a class derived from an abstract class with a where clause cast to its lowest common class

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

like image 334
Robert Avatar asked Jan 23 '12 15:01

Robert


People also ask

Can abstract class inherit another abstract class?

An abstract class can extend another abstract class. And any concrete subclasses must ensure that all abstract methods are implemented. Abstract classes can themselves have concrete implementations of methods. These methods are inherited just like a method in a non-abstract class.

Can abstract class have non abstract methods?

Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods.

Can abstract class have main method?

We can run abstract class in java like any other class if it has main() method.

Why abstract class is used in C# with example?

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.


1 Answers

You're getting the error because Request<Response> and Request<LoginResponse> are not covariant.

Just because LoginResponse inherits from Response doesn't mean that Request<LoginResponse> can be treated the same as Request<Response>. Give this article a read:

MSDN - Covariance and Contravariance in Generics

like image 172
Justin Niessner Avatar answered Oct 07 '22 00:10

Justin Niessner