Overriding an abstract property with a derived return type in c#

Trevor picture Trevor · Jun 15, 2011 · Viewed 13.5k times · Source

I have four classes. Request, DerivedRequest, Handler, DerivedHandler. The Handler class has a property with the following declaration:

public abstract Request request { get; set; }

The DerivedHandler needs to override this property so that it returns DerivedRequest instead:

public override DerivedRequest request { get; set; }

Does anyone have any ideas about how to make this work?

Answer

Jamie Treworgy picture Jamie Treworgy · Jun 15, 2011

This isn't really a good way to structure things. Do one of the following

1) Just don't change the return type, and override it normally in the subclass. In DerivedHandler you can return an instance of DerivedRequest using the base class signature of Request. Any client code using this can choose to cast it to DerivedRequest if they want to.

2) Use generics instead if they are not supposed to be polymorphic.

public abstract class HandlerBase<T> where T: Request
{
    public abstract T Request {get;set;}
}

public class Handler: HandlerBase<Request>()

public class DerivedHandler: HandlerBase<DerivedRequest>()