Eitan
Eitan

Reputation: 173

Casting Generic type to base type

I have the next scenario:

public class RequestBase { }
public class ResponseBase { }

public interface IService<TRequest, TResponse>
           where TRequest : RequestBase where TResponse : ResponseBase
{
    TResponse Execute(TRequest request);
}

public class MyRequest : RequestBase { }
public class MyResponse : ResponseBase { }

public class MyService : IService<MyRequest, MyResponse>
{
    public MyResponse Execute(MyRequest request)
    {
        return new MyResponse();
    }
}

now i am creating factory that will create my service:

class ServicesFactory
{
    public IService<RequestBase, ResponseBase> Create()
    {
        var service = new MyService();
        return (IService<RequestBase, ResponseBase>)service;
    }    
}

The problem is that the casting throw exception.

How can I cast the derived type to the base type?

Upvotes: 0

Views: 295

Answers (1)

milleniumbug
milleniumbug

Reputation: 15804

Make your interface covariant on TResponse:

public interface IService<TRequest, out TResponse>

and you'll be able to convert MyService to IService<MyRequest, ResponseBase>. Note that it isn't possible to convert to IService<RequestBase, ResponseBase>, because not all RequestBases are MyRequests.

That said, you can decorate MyService with a different class that will check at runtime whether passed in RequestBase is actually MyRequest. This, of course, violates LSP if the interface expects any RequestBase.

Upvotes: 3

Related Questions