An interface is pretty similar to an abstract class where all methods are abstract, but because classes can implement many interfaces, as opposed to inheriting from a single abstract class, it is quite a bit more flexible.
interface IEquatable<T>
{
bool Equals(T obj);
}
Any class or struct which implements the IEquatable interface must contain a
definition for an Equals method. As a result, you can call this method on any
class implementing this interface.
implementing an interface
To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
public class Car : IEquatable<Car>
{
public string? Make { get; set; }
public string? Model { get; set; }
public string? Year { get; set; }
// Implement IEquatable interface.
public bool Equals(Car? car)
{
return (this.Make, this.Model, this.Year) == (car?.Make, car?.Model, car?.Year);
}
}
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
NOTE: You do not use the override keyword when implementing an interface as you are not overriding default behaviour, but simply fulfilling the interface's contract.