locked
What can an Interface do? RRS feed

  • Question

  • Hello friends,
    I am reading an Apress Pro book on C# .Net and it does not describe very well what are the advantages of Interfaces, all I got out of it was that Interfaces can be used on many classes which do not have to share the same derived parent class, while this sounds great they also seem to have limitations: no constructors, can't declare new fields, etc... And from the example in this book they just show an interface with some blank methods, and then when they use the Interface they write the function for that method again?! Is it just a bad example or am I not seeing something, because from what I got you cannot do very much with interfaces.

    Thanks for any ideas or input.
    Sunday, December 6, 2009 9:13 AM

Answers

  • Hi,

    Here is a defination from http://www.csharp-station.com/Tutorials/lesson13.aspx

    An interface looks like a class, but has no implementation. The only thing it contains are definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined.

    So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

    To say it in basic words interfaces gives the ability of your class to do something, but does not tell how your class do it.

    For example let's assume you have an interface like IMusicPlayable and a Play method in it.

    You can implement this interface into CdPlayer class or Casette player class, but both of these classes logic of playing music is totally different. So you have to write different codes in play method.

    But if you know that a class implemented IMusicPlayable interface when you call Play method it will play music.

    Let me give you an example.

        public interface IClear
        {
            void Clear();
        }

    in MyTextBox class that derived from IClear interface

            #region IClear Members

            public void Clear()
            {
                this.Text = "";
            }

            #endregion

    In Combobox class that derived from IClear interface

            #region IClear Members

            public void Clear()
            {

                this.SelectedIndex = -1;
            }

            #endregion

    And i can call them from my form like which my form also implements IClear.

            #region IClear Members

            public void Clear()
            {
                Clear(this);
            }

            #endregion
            private void Clear(Control parControl)
            {

                for (int i = 0; i < parControl.Controls.Count; i++)
                {
                    if (parControl.Controls[i] is IClear)
                    {
                        ((IClear)parControl.Controls[i]).Clear();

                    }
                    Clear(parControl.Controls[i]);
                }
            }

    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 9:47 AM
  • Hi,

    Interfaces are very useful, they are mainly about breaking dependencies in code... polymorphism. Give you an example...

    If you have code like this....

    string[] data = File.ReadAll(file)

    then your application can only read data from a file with a single fomat and thats it. Application is stuck with it.

    If you define an interface like this

    interface IDataReader
        string[] ReadData(string file)

    Then you can create all sorts of data sources

    class FileReader : IDataReader
        string[] ReadData(string file)
            return File.ReadAll(file)

    can be used like this

    IDataReader reader = new FileReader
    string[] data = reader.ReadData(file)

    or like this....

    IDataReader reader = new XmlFileReader
    string[] data = reader.ReadData(file)

    So the application becomes less dependent on things with interfaces, here the application isn't dependent on one file format but can change really easy without a lot of work.

    Interfaces are also really good for unit testing code because you can mock / stub out parts of the application based on interface.

    They are very useful and it's worth really understanding what they are about and what they do. 

    Hope that helped, any more questions please post. 

    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 11:43 AM

  • An interface defines a contract.  If a class implements an interface then you know for sure there is some implementation of whatever is defined in the interface.

    For example, you could have the IShape interface which defines a method called GetArea(); then you could have classes such as Circle, Square, and Triangle which implement the IShape interface and thus must implement a method which will return the area of the given shape.

    Further still you can then do things like the following:

    public void SomeMethod(IShape shape)
    {
        Double area = shape.GetArea();
    }

    This method doesn't know whether you passed it a Circle, Square, or Triangle but it does know it can use anything defined by the IShape interface.
    • Proposed as answer by JediJohn82 Monday, December 14, 2009 4:28 PM
    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 7:07 PM
  • "Or is the interface simply a checking tool that guarantees whether a class has the ability to use a certain method or not but does not actually define how the method works?"

    That's it!!

    It's like the interface is used to define behaviour; all classes that implement the interface have that behaviour (although they may implement it differently).

    You can swap out different implementations of the behaviour by 'coding against the interface' which is what my example above did, coded against IDataReader.
    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Monday, December 7, 2009 10:08 AM

All replies

  • Hi,

    Here is a defination from http://www.csharp-station.com/Tutorials/lesson13.aspx

    An interface looks like a class, but has no implementation. The only thing it contains are definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined.

    So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

    To say it in basic words interfaces gives the ability of your class to do something, but does not tell how your class do it.

    For example let's assume you have an interface like IMusicPlayable and a Play method in it.

    You can implement this interface into CdPlayer class or Casette player class, but both of these classes logic of playing music is totally different. So you have to write different codes in play method.

    But if you know that a class implemented IMusicPlayable interface when you call Play method it will play music.

    Let me give you an example.

        public interface IClear
        {
            void Clear();
        }

    in MyTextBox class that derived from IClear interface

            #region IClear Members

            public void Clear()
            {
                this.Text = "";
            }

            #endregion

    In Combobox class that derived from IClear interface

            #region IClear Members

            public void Clear()
            {

                this.SelectedIndex = -1;
            }

            #endregion

    And i can call them from my form like which my form also implements IClear.

            #region IClear Members

            public void Clear()
            {
                Clear(this);
            }

            #endregion
            private void Clear(Control parControl)
            {

                for (int i = 0; i < parControl.Controls.Count; i++)
                {
                    if (parControl.Controls[i] is IClear)
                    {
                        ((IClear)parControl.Controls[i]).Clear();

                    }
                    Clear(parControl.Controls[i]);
                }
            }

    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 9:47 AM
  • Hi,

    Interfaces are very useful, they are mainly about breaking dependencies in code... polymorphism. Give you an example...

    If you have code like this....

    string[] data = File.ReadAll(file)

    then your application can only read data from a file with a single fomat and thats it. Application is stuck with it.

    If you define an interface like this

    interface IDataReader
        string[] ReadData(string file)

    Then you can create all sorts of data sources

    class FileReader : IDataReader
        string[] ReadData(string file)
            return File.ReadAll(file)

    can be used like this

    IDataReader reader = new FileReader
    string[] data = reader.ReadData(file)

    or like this....

    IDataReader reader = new XmlFileReader
    string[] data = reader.ReadData(file)

    So the application becomes less dependent on things with interfaces, here the application isn't dependent on one file format but can change really easy without a lot of work.

    Interfaces are also really good for unit testing code because you can mock / stub out parts of the application based on interface.

    They are very useful and it's worth really understanding what they are about and what they do. 

    Hope that helped, any more questions please post. 

    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 11:43 AM
  • Thanks for the excellent examples, I am almost understanding it. However one question still bothers me. In the first reply by Tamer Oz, in the example, a method is defined in the interface: 
      public interface IClear
        {
            void Clear();
        }


    And then in the class code itself we see once again: 

            public void Clear()
            {
                this.Text = "";
            }

    and again: 

            {

                this.SelectedIndex = -1;
            }

    Now I come back to my question, so why did we define that interface in the first place, if we did not say what that method does and had to rewrite what the method does in the class itself anyways?

    Edit: Or is the interface simply a checking tool that guarantees whether a class has the ability to use a certain method or not but does not actually define how the method works?

    Thanks again.

    Sunday, December 6, 2009 4:03 PM

  • An interface defines a contract.  If a class implements an interface then you know for sure there is some implementation of whatever is defined in the interface.

    For example, you could have the IShape interface which defines a method called GetArea(); then you could have classes such as Circle, Square, and Triangle which implement the IShape interface and thus must implement a method which will return the area of the given shape.

    Further still you can then do things like the following:

    public void SomeMethod(IShape shape)
    {
        Double area = shape.GetArea();
    }

    This method doesn't know whether you passed it a Circle, Square, or Triangle but it does know it can use anything defined by the IShape interface.
    • Proposed as answer by JediJohn82 Monday, December 14, 2009 4:28 PM
    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Sunday, December 6, 2009 7:07 PM
  • "Or is the interface simply a checking tool that guarantees whether a class has the ability to use a certain method or not but does not actually define how the method works?"

    That's it!!

    It's like the interface is used to define behaviour; all classes that implement the interface have that behaviour (although they may implement it differently).

    You can swap out different implementations of the behaviour by 'coding against the interface' which is what my example above did, coded against IDataReader.
    • Marked as answer by Harry Zhu Wednesday, December 16, 2009 8:23 AM
    Monday, December 7, 2009 10:08 AM
  • As JediJohn82 answered, it seems that interface has something like polymorphism. So why don't we use polymorphism with the keyword virtual instead ? What is the difference to the using of polymorphism ? Thank you so much !
    Thursday, November 11, 2010 3:17 PM