DEV Community

Discussion on: ELI5: Why cast to an interface?

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

There are only a few situations where I've explicit cast to an interface:

  • I am downcasting from a less-specified type, such as object or a base class. That is, an implicit cast doesn't work in these situations.
  • I'm trying to call an interface function in C# which is exposed only on the interface (it's a C# oddity)
  • I'm forcing selection of a function overload where multiple might work (such as when a class implements multiple interfaces and both have functions). This is a hack and usually indicates an API defect.

The idea of casting to an explicit interface just to limit the interface, used locally in a function, seems like an anti-pattern to me: the function is mixing multiple divergent purposes. If you have the full object then you can use it. If you're making generic code then put it in a function that takes only the interface.

Collapse
 
lluismf profile image
Lluís Josep Martínez

I agree 100% it's an anti-pattern.