How will I know when to create an interface?

it solves this concrete problem:

you have a, b, c, d of 4 different types. all over your code you have something like:

a.Process();
b.Process();
c.Process();
d.Process();

why not have them implement IProcessable, and then do

List<IProcessable> list;

foreach(IProcessable p in list)
    p.Process();

this will scale much better when you add, say, 50 types of classes that all do the same thing.


Another concrete problem:

Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.


I like Jimmy's answer a lot, but I feel I need to add something to it. The key to the whole thing is the "able" in IProcessable . It indicates a capability (or property, but meaning "intrinsic quality", not in the sense of C# properties) of the object that implements the interface. IAnimal is probably not a good example for an interface, but IWalkable might be a good interface to have if your system has many things that can walk. You might have classes derived from Animal such as Dog, Cow, Fish, Snake. The first two would probably implement IWalkable, the latter two don't walk, so they wouldn't. Now you ask "why not just have another superclass, WalkingAnimal, that Dog and Cow derive from?". The answer is when you have something completely outside the inheritance tree that also can walk, such as a robot. Robot would implement IWalkable, but probably wouldn't derive from Animal. If you want a list of things that can walk, you type it as IWalkable and you can put all walking animals plus robots in the list.

Now replace IWalkable with something more software-y like IPersistable, and the analogy becomes much closer to what you'd see in a real program.


Use interfaces when implementations of the same functionality will differ.

Use a abstract/base classes when you need to share a common concrete implementation.