An IComparable
class provides a CompareTo
method that compares two objects and determines
their ordering, an IEquatable
class provides an Equals
method that determines whether an object is equal to another object, an IEnumerable
class provides a GetEnumerator
method that returns an IEnumerator
object that has MoveNext
and Reset
methods for moving through a list of objects, an ICloneable
class provides a Clone
method that returns a copy of an object, et cetera.
Why do we need to implement these interfaces to provide this functionality? Could we not just define an Equals
, GetEnumerator
, MoveNext
, Reset
, and Clone
method without implementing the interface?
I suspect this has something to do with using two objects at once (e.g., for comparing) and you need some sort of overarching class to do this, but I cannot wrap my head around it. Or maybe the interface does provide some extra functionality that otherwise would not be possible (e.g., IDisposable seems to be a necessary marker sometimes)? I hope someone can explain why everybody implements interfaces instead of just providing the functionality in the class itself.
Why do we need to implement these interfaces to provide this functionality?
So that other code can be written in terms of the interface, and work with objects of types which implement the interface without knowing about the specific types. The compiler ensures at compile-time that the relevant members are present. For example, consider this method:
public T Max<T>(T first, T second, IComparer<T> comparer)
{
return comparer.Compare(first, second) > 0 ? first : second;
}
The compiler needs to make sure that the comparer.Compare
method call makes sense - and it only does make sense because IComparer<T>
specifies the method. You wouldn't want to have to write that method for every class that implements an appropriate Compare
method... the interface allows us to express the commonality between the classes, and write the Max
method once to handle all classes with that common behaviour.
This is because C# is a statically typed language - if it were dynamically typed, there wouldn't be a need for interfaces.
See more on this question at Stackoverflow