...worded in a way a programmer might
understand.
If you are not a programmer, you're going to have a little trouble understanding interfaces. Without a fairly good understanding of basic object-oriented principles, this might seem a little confusing. But onwards:
Interfaces are similar to classes, but instead of telling you what an object is it tells you what it does.
For example, a very common interface is IEnumerable
. When a class implements that interface, it means that the object can create and return an Enumerator
, which can be consumed by some other part of code (usually a foreach
loop, or a LINQ
query).
Another one you might see a lot is IDisposable
. This means that you call call .Dispose()
on the object and it will clean up resources. It doesn't say anything about what resources it'll clean up or what the object is -- it could be a StreamReader
or a SqlConnection
or something. All it says is that it has a method called Dispose
.
Interfaces are very useful concepts. If you have a lot of classes that are very different but share a certain common behavior, you can have them all implement a single interface and then operate on them as one. For example, if you had an interface:
interface ICanPrintMyContents
{
void PrintContents();
}
Then a bunch of classes that implemented them:
class ParkingGarage : ICanPrintMyContents { ... }
class UnimpressivePolitician : ICanPrintMyContents { ... }
class BankingSimulation : ICanPrintMyContents { ... }
You could put them all in a list together, even though there's no real relation between their classes.
List<ICanPrintMyContents> list = { theGarage, insertNameHere, sim1, anotherGarage };
foreach(ICanPrintMyContents item in list)
list.PrintContents();
(Note: that ICan...
naming convention is not widely used, and I don't advise it. Many people don't like it, but I'm using it here because it conveys the meaning of the interface very well. More common would be IPrintableContents
or something)