Reputation: 457
I have a question on how to be in cases when I build the hierarchy on interface, then I have the base abstract implementing class and many subclasses - concrete implementors. But say one of the subclasses has 2 extra properties that are not included in the interface. But I need them when I work with interface. Is it a bad practice to cast from interface to the direct concrete class? Or maybe I would formalize this case (2 extra properties not included in interface) as a new extension of base interface through inheritance, when one interface inherits from another one, so it would be safe to cast not to class, but to derived interface. What choice is the most corrective?
Here's an example:
public interface IToken {
string Tag {get;}
string Content {get;}
object CalculatedValue {get; set;}
string ValueFormat {get;}
}
// inheritance of interface
public interface ISimpleToken: IToken {
string Key {get; set;}
}
// OR!!!!!
class SimpleToken: IToken {
// ....interface members
....
public string Key {get; set; }
}
Upvotes: 1
Views: 915
Reputation: 7680
The general rule of thumb is if you are going to expose your API through interfaces, you should uses interfaces throughout. Your interfaces should only include things you want to publicly expose. If it's something you just need inside of the implementation of that interface it goes in the class.
The other part, "it depends". Usually with the way you are headed, at some point, you're going to want a collection of all of those implementations and so you would need to refer to them by the common base interface/class.
EDIT: if you find that you need to cast interfaces from the base class, you are "probably" doing something wrong. If multiple interfaces have the same method, it belongs in the base interface. You can do this with generics.
If you have a scenario where the derived classes need to do something different from the base class, then you should use virtual methods and overrides.
Adding something into a derived class is fine as long as it doesn't change the interface which it shouldn't since if you are using interfaces, you generally don't want to expose the implementation classes.
Upvotes: 3