C# Design – Coding to Interfaces

cdesign

I understand why it is a good idea to code to an interface rather than to a concrete class. I find it hard to implement though as other methods generally need to use properties of the given object. Have I got the wrong end of the stick?

Best Answer

I don't see why needing properties matters. Don't focus on what you need to perform the operation, but rather what operations are needed. The data needed to perform said operations will be determined by the implementing classes.

For example, you have a Shape interface. One of the methods in this interface is getArea(). You say that anything that is a Shape must be able to calculate its area - that implies that it must have the appropriate properties and members to do so. If a Circle class implements the shape interface and needs a getArea() method, that implies that (since getArea() doesn't take any parameters), that the Circle instance must be aware of it's radius. If a Rectangle class implements the Shape interface, that implies that it must somehow maintain its length and width.