✅ understanding interfaces
An interface is supposed to provide extra functionality for a class.
but the class has to manually implement the method specified in the interface
then whats the point of having an interface if you're going to create the custom method anyway?
5 Replies
An interface is supposed to provide extra functionality for a classthis is an incorrect assessment interfaces provide contracts for other types to implement with them, an api can take the interface as an input and call methods on said interface instance, regardless of how it was implemented take
System.Linq
for example, which provides extension methods on IEnumerable<T>
, an interface for enumerable collections
many classes implement IEnumerable<T>
; List<T>
, arrays, Dictionary<TKey, TValue>
, HashSet<T>
, the list goes on. and you can even make your own classes that implement IEnumerable<T>
.
all of those are usable with Linq
because they all provide their own implementation of the contract that IEnumerable<T>
provides
or take IParsable<T>
as an example; it provides a contract where T
must implement a way to be created from a string
such an interface could be used in this (very naive, but it gets the point across) way:
you can see here that you can generically pass any T
into ParseAs
, as long as it implements IParsable<T>
how this parsing happens is implemented in the concrete type of T
itself, like this;
i can now use ParseAs<Point>("0, 0")
from before without any issues, because Point
does have its own custom implementation of the IParsable
interfaceSo it's guarantees a standard set of rules for the class or object to have so you can guarantee some sort of basic functionality
that's the gist of it
Makes sense thanks
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.