Implementing Interface Members Explicitly


Implementing Interface Members Explicitly

The problem with simply adding public members to implement the interface is that sometimes two interfaces have the same method name and same parameters, but the methods need to have a different implementation. If you use the implicit method, then the one public method would implement every interface method with the same name and parameters. The explicit method lets you tell the compiler which method in which interface you meant to implement.

To implement an interface explicitly:

  1. After the name of the class that will implement the interface type a colon followed by the name of the interface you wish to implement.

  2. Type the return type of the interface member.

  3. Type INameOfInterface.InterfaceMethod . In other words, type the name of the interface followed by a period followed by the name of the interface method.

  4. Type the parameters for the member.

  5. Write the code for the member ( Figure 8.11 ).

    Figure 8.11 When implementing interfaces explicitly you don't add any access modifiers, then you write the name of the interface followed by a period followed by the method name.
     public interface IHuman {    string Name { get; }    void Sleep(short hours); } public class Person : IHuman {  string IHuman.Name  {      get      {         return "Paul";      }    }  void IHuman.Sleep(short hours)  {      for (short counter=0;      counter < hours; counter++)      {         HttpContext context =         HttpContext.Current;         context.Response.Write("Snore!");      }    } } 

graphics/tick.gif Tip

  • All methods that you implement in this fashion are private. You can't add an access modifier in front of the definition.




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