#438 – Benefits of Using Interfaces

You might wonder why you’d define an interface, have a class implement that interface and then access the class through the interface instead of just using the class directly.

One benefit of interfaces is that it allows you to treat different types of objects in the same way, provided that they implement a common interface.

For example, assume that we have Dog, Seal and DrillSergeant classes, all of which implement the IBark interface (which contains a Bark method).  We can now store a collection of instances of these classes and ask all objects in our collection to Bark by using the IBark interface.

            Dog kirby = new Dog("Kirby", 12);
            Seal sparky = new Seal("Sparky");
            DrillSergeant sarge = new DrillSergeant("Sgt. Hartman", "Tough as nails");

            List<IBark> critters = new List<IBark>() { kirby, sparky, sarge };

            // Tell everyone to bark
            foreach (IBark barkingCritter in critters)
            {
                barkingCritter.Bark();
            }