I am trying to develop a simple interface for allowing quick lists to be generated from classes. Basically, the interface needs to return an ID and a Name. However, some classes have a calculated name property which is read only, others just use a read/write name property. Basically, all I care is that it has a getter, it does not matter if the property has a setter. How can I write this interface to handle either or without throwing compile errors?
I have read this question and didn’t really follow it, maybe I am just dense. If so, please show me the error of my ways 🙂
Looks like the answer from the other question will work: here’s a sample:
The above approach will actually result in classes that implement IReadWrite also implementing IReadOnly–so you’ll actually need to downcast to IReadWrite in order to set the property.
Another approach, which avoids that issue but requires a little more logic in the implementing classes and their caller’s is something like:
Update: To answer the question about downcasting; “downcasting” is a term used to describe casting an object from a superclass, interface, or abstract base class
Typeinto a more concreteType.For example, the first example above defines two interfaces:
IReadOnlyandIReadWrite. You’ll notice thatIReadWriteimplementsIReadOnly, which means that you can make bothIReadWriteandIReadOnlycalls to objects which implementIReadWrite.Since
IReadWriteimplementsIReadOnly,IReadWriteis said to be a “sub-class” ofIReadOnly(although “sub-class” is more accurately used to describe a class which inherits a base class, rather then implements an interface–for the sake of simplicity they are very nearly the same concept). IfIReadWriteis a sub-class ofIReadOnly, then the inverse is true–IReadOnlyis a super-class ofIReadWrite.For example, I can describe an instance of
ReadWriteClassas an implementation of either interface: