Interfaces are contracts that classes or structs can define. An object can implement multiple interfaces (but in C#, can derive from only one base class). As a general rule, these interfaces’ name starts with a capital I, and then the interface name. Interfaces cannot contain member variables, or defined methods, just the signatures of the methods to be implemented. An example:
interface IMyFace
{
bool IsReusable(object otherObject);
int objID {get;set;}
}
Interfaces can implement each other. The most important interfaces of the .NET Framework are as follows:
.NET Interfaces | |
IClonable | Defines the Clone method, which helps you create an instance of the class with the exact same values (fields and properties). |
IComparable | Defines the CompareTo method to implement type-specific comparsion methods. This method should return a negative value if your instance is less than the supplied object, positive if it is greater and 0 if they are equal. |
IConvertible | Provides a bunch of methods for converting the given object to a common CLR type (int, short, long, etc.). |
IDisposable | Defines the Dispose void. You should free up all unmanaged resources that your object uses in this method. |
IEquatable | A generic interface. Defines the generic Boolean Equals method, in which you can return true if your instance is equal to the provided generic-type other instance. |
IFormatable | Provides an overload of the ToString method, in which you can specify a format string and an IFormatProvider. |
Further Readings