Sunday, April 03, 2011

Explicitly Implementing Interface

 

Explicit implementation can be helpful when class implements interfaces having save method signatures

interface IAgency
    {
        void AddUpdate();
    }
    interface IPackage
    {
        void AddUpdate();
    }
    class Travel : IAgency, IPackage
    {
        public void AddUpdate()
        {
        }
    }


By Implementing Interfaces explicitly we can avoid the above problem



interface IAgency
{ 
    void AddUpdate();    
}
interface IPackage
{ 
  void AddUpdate();    
}
class Travel : IAgency,IPackage
    {
        
        void IAgency.AddUpdate()
        {
            throw new NotImplementedException();
        }
        void IPackage.AddUpdate()
        {
            throw new NotImplementedException();
        }
}


Travel obj = new Travel();
//obj.AddUpdate();  // Compiler error.
IAgency objAgency = (IAgency)obj;
objAgency.AddUpdate();  // Calls IAgency.AddUpdate on Travel 
IPackage objPackage = (IPackage)obj;
objPackage.AddUpdate(); // Calls IPackage.AddUpdate on Travel 

No comments: