Deriving One Interface from Another


If other developers are using your object through a particular interface, and you need to enhance the interface, it's best to leave the original interface definition intact. C# provides a mechanism by which you can extend the interface without adding methods to the original interface. The mechanism is to derive one interface from another.

To derive one interface from another:

  1. Assuming you have one interface already defined, define a new interface.

  2. After the name of the interface type a colon , then NameOfFirstInterface , where NameOfFirstInterface is the name of the interface you wish to extend.

  3. You can implement both the original interface as well as the new interface in the same class ( Figure 8.25 ).

    Figure 8.25 IPresident extends IParent. That means that if you implement the IPresident, not only do you have to implement the methods in IPresident but the methods in IParent as well.
     interface IParent {    void SendKidsToPlay(); } interface IPresident : IParent {    void DispatchArmy(); } class George :  IPresident  {  //implment the methods for both   //IParent and IPresident  public void SendKidsToPlay()    {    }    public void DispatchArmy()    {    } } 

graphics/tick.gif Tips

  • The classes in Figures 8.26 have equivalent definitions. Implementing the original and the derived interfaces is the same as implementing the derived interface only. Both result in a class that is compatible with both interfaces.

    Figure 8.26 It's the same thing to implement both the parent interface and the derived interface as it is to implement just the derived (because the derived contains the parent members as well.)
     interface IParent {    void SendKidsToPlay(); } interface IPresident : IParent {    void DispatchArmy(); } class George :  IPresident  {  //implment the methods for both   //IParent and IPresident  public void SendKidsToPlay()    {    }    public void DispatchArmy()    {    } } 
  • The classes in Figures 8.27 are not equivalent definitions. Even though IGivingPerson is a combination of IPerson and ISendsGifts, implementing IGivingPerson is not the same as implementing IPerson and ISendsGifts separately. A good way of thinking about this is that IGivingPerson could have methods other than the combination of IPerson and ISendsGifts.

    Figure 8.27 Even though Telemarketer implements both IPerson and ISendsGifts, the class is not compatible with the IGivingPerson interface.
     interface IGivingPerson : IPerson, ISendsGifts { } class Grandma :  IGivingPerson  { } class Telemarketer :  IPerson, ISendsGifts  { } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net