Oded's answer solves the compilation problem by letting you define a ToDerived method that satisfies the interface. However, as I said in a comment, I'm not quite sure if this is the best implementation.
The main problem that I am facing is that such conversion methods are usually needed in a static context. You do not have an instance of SalesUser; you want, and you have a User, so you call the method in a static context ( SalesUser.ToDerived(myUser)
), and you get SalesUser (the method will have a more suitable name FromUser () or similar). The method specified in the interface requires that you already have SalesUser in order to convert the user to SalesUser. The only situation I can think of in which you really need an existing SalesUser is a "partial clone"; You create a new instance of SalesUser using information from both the user transferred and from the SalesUser to which you are calling the method. In all other cases, you either donβt need SalesUser (conversions that should be static, as indicated), or you donβt need a user (the clone or deep copy method that creates a new instance with the same data as the instance, on which you called the method).
In addition, users of your class must be aware that they must call ToDerived () in order to convert from user to SalesUser. Typically, a C # programmer expects an explicit or implicit conversion to be available:
public class SalesUser { public static explicit operator (User user) {
... OR, without receiving a conversion operator, one would expect him to be able to build SalesUser using User:
public class SalesUser:IUser { public SalesUser(User user) {
Now static members do not satisfy interface definitions, and interfaces cannot define static elements or constructor signatures. This tells me that the IUser interface should not try to define a conversion method; instead, methods that need some kind of IUser can simply specify this, and the user can provide the implementation as needed without an implementation that needs to know that it can convert to itself.
source share