An interface is a contract: when you add an Interface to your class you are agreeing to abide by the rules that the interface lays down, and in return it allow your class to join the exclusive membership club, and get the benefits of that membership, no matter what they might be.
For example, all arrays, and Generic Collection objects (such as List<T>) implement IEnumerable, and as a result they are all usable in a
foreach
loop - if your class implements the IEnumerable Interface, then it can be used in
foreach
as well.
I use them a reasonable amount. Recently, I needed a panel which contained controls which it auto sized, depending on which were Expanded and which were Shrunken. So I created a FlexPanel to hold them, and an IFlexPanel interface which the controls had to implement:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UtilityControls
{
public interface IFlexControl
{
void Shrinking();
void Expanding();
event EventHandler RequestShrink;
event EventHandler RequestExpand;
event EventHandler RequestToggleSize;
bool DefaultShrunken { get; set; }
}
}
Provided the control implemented the two methods "Shrinking" and "Expanding", the three events "RequestShrink", "RequestExpand" and "RequestToggleSize" and the property "DefaultShrunken" they could be based on any Control or UserControl and they would be autosized as necessary.
Using an interface here means that I don't have to restrict myself later to having to use controls based on a Button, or a DataGridView, or even a UserControl - anything which implements IFlexControl will be fine. Remember, C# only allows you to derive your class from a single class - so if I constructed IFlexControl as a normal or abstract class then only controls derived from that class coule be loaded into a FlexPanel.
[edit]Code block changed from "xml" to "c#" - I didn't notice before I posted - OriginalGriff[/edit]