c# - Implementing interface but returning a subclass of the return type? -


i working asp.net mvc in c#. creating service classes. have service interface driver service interfaces (idriverservice).

it has following method definition:

driver new(); 

i have 2 implementations of interface implements method such:

driver new() {    return new driver(); }  driver new() {    return new subclassofdriver(); } 

as can see 1 implementation implements new method returning base driver, , other subclass of driver.

the problem implementing interface have return 'driver' want return 'subclassofdriver'. should cast result driver want unsafe , coder require information implementation acertain driver has been instantiated. what's best way of doing this?

thanks

you can overload return type using explicit interface implementation:

driver idriverservice.new() {    return new(); // calls method below }  public subclassofdriver new() {    return new subclassofdriver(); } 

now code knows implementation as implementation of interface see explicit interface implementation method, , expect return type of driver.

any code refers service via concrete type see second method, , expect return type of subclassofdriver. example:

specialfactory specialfactory = new specialfactory(); subclassofdriver subclassdriver = specialfactory.new(); // fine idriverfactory generalfactory = specialfactory; idriver generaldriver = generalfactory.new(); // fine // wouldn't compile subclassofdriver invalid = generalfactory.new(); 

alternatively, might want make interface generic:

public interface idriverfactory<tdriver> tdriver : driver {     tdriver new(); }  public class specialdriverfactory : idriverfactory<subclassofdriver> {     public subclassofdriver new()     {         return new subclassofdriver();     } } 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -