Tuesday, June 28, 2016

Interfaces


  • We can only have internal access modifier for an interface (if we don't define also by default access modifier is internal for interface)
  • Interface can contain only signature of methods, properties, events or indexers

Decoupling can be Achieved through Interface



Lets say we have accounts class and invoice class. 
Now rather than communicating directly classes to classes (concrete classes), we can put a interface in between and both of these classes communicate via the interfaces

Example

interface IDBInterface
{
   void Update
}

class SQL : IDBInterface
{
  public void Update()
   {
     MessageBox.show("Updating SQL server.....");
   }
}

class Oracle : IDBInterface
 {
   Public void Update()
   {
     MessageBox.show("Updating oracle server...");
   }
}

class CommunicationChannel
{
  public void Update(IDBInterface idb)
  {
    idb.Update();
  }
}

=====================================================================
//Calling class
Class Myclass
{
  public void XYZ()
  {
    IDBInterface idb = new Oracle();
    CommunicationChannel cmc = new CommunicationChannel();
    cmc.Update(idb);
  }

Communication channel class is not directly communicating with concrete classes, it is communicating via interface. We can inject any class to communication channel class and the communication channel class will call the method.


======================================================================



Explicit Interface calling



interface Icontrol

{
  void paint();
}

interface Isurface
{
  void paint();

}

Way1 to call interface

class SampleClass : Icontrol,Isurface
{
  public void paint()
   {
      console.writeline("Hi");

   }
}

Explicit Calling (Way 2) 

class SampleClass : Icontrol,Isurface
{
   void Icontrol.paint()
    {
      console.writeline("IControl.paint");
     }
   void Isurface.paint()
    {
      console.writeline("Isurface.paint");

     }
}

No comments:

Post a Comment