I’m a little confused on the concept of methods returning interfaces. Is there an article or reference that discusses this in some detail? I’m confused on when/why you might want to do this, and how is it that you can cast an interface to/from the object it’s associated with (I think that’s right).
I’m a little confused on the concept of methods returning interfaces. Is there an
Share
Returning an interface is good when you want to separate the contract of what something is supposed to do, from the concrete implementation (how it does it). Having an interface allows you to reuse and modify code more easily.
If you have an interface
IFooand an implementationSimpleFoothat implementsIFooin a naive way you can program against the interface and get basic functionality. Later you can make anAdvancedFooimplementation that also implements the sameIFoointerface. Now you just need to return your new object and the rest of the code will use the new, more advanced class without requiring any changes. Having the interface also allows you to make the choice of which class to use at runtime.When your code returns interfaces it also makes it more flexible. You may currently return a
List<T>but if the result only needs to be used as anIEnumerable<T>then you should return this instead. Then you can later change your implementation so that the results are generated on the fly (for example with an iterator block) and the calling code will still work.The whole point of interfaces is that you shouldn’t need to do this. You should just use the interface without worrying about what the specific implementation is. The correct method will be called by the runtime. If you think you need to cast it could be a sign that your interface is not rich enough to support your needs.
You can cast if you need to though:
Note that this cast can fail and you may want to use
asinstead: