Use of Interfaces or Contracts in C# and .NET Framework
Interface provides standardization across multiple objects. By implementing an interface we specify that certain method must be implemented. This allows us to design objects with predictable behavior and this in turn helps to standardize our development environment so we know what to expect from the object which implements known interface.
For example by implementing IComparable we know that we will get method which compare objects. Visual Studio makes it easy for you to generate code for method that you must implement. Just click on the IComparable with the right button select Implement Interface twice and code will pop inside your class. This interface can also be used for sorting of our class objects. It returns negative is value we are comparing to is less, zero if equal and positive integer if it is the same value.
class myClass : IComparable
{
int myInt = 0;
public int CompareTo(object obj)
{
throw new Exception("The method or operation is not implemented.");
}
}
Most used interfaces are: IComparable, IDisposable, IConvertible, ICloneable, IEquatable, IFormattable.
You can also define your own interfaces for the reasons just explained above.
interface IMyInterfce
{
// Forwards the message. Returns True is success, False otherwise.
bool Forward();
// The message to forward.
string MyMessage { get; set; }
// The Address to forward to.
string MyAddress { get; set; }
}