#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();
            }


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #438 – Benefits of Using Interfaces

  1. ocaccy says:

    Hi Sean.

    I have an application with 6 devices RS485 connected to the PC via converter RS485/USB.
    The command to access the devices is:
    ID01, ID02, ID03, ID04, ID05, ID06.

    If only one device is connected, for example ID01. I like this: com.Send (“id01”) and the device then responds.

    However if I have more than one device, I need to send the same command 2 times.
    You have some knowledge of serial communication with C #?
    Or you can show me some material on this subject.

    Another thing, how to change the flow of a method or placing between two methods a third method?

    Best Regards,
    ocaccy

    • Sean says:

      Sorry, I don’t have any experience with serial port communication. I’d start with documentation for whatever library you’re using to do the communication.

      I’m not sure what you mean by “placing between two methods a third method”. Just change your calling code to call the third method after the first..

      e.g.:
      callMethod1();
      callMethod3();
      callMethod2();

Leave a comment