Tuesday, November 14, 2017

Difference between Implicit implementation and Explicit implementation of interface


In case of implicit public keyword is necessary in function definition while in case of Explicit declaration public keyword can not be use and we need to define it with Interface Name and this method will be public by default.

Explicit Implementation

 public interface IUser2
    {
        void Display();
    }

    public class User1 : IUser2
    {     
        void IUser2.Display()
        {
            throw new NotImplementedException();
        }
    }

In case of explicit implementation you can not use as below

User1 obj = new User1();
obj.Display(); //Error , event intellisence will not show method Dispaly with obj.

Correct use is

IUser2 obj = new User1();
obj.Display();

Implicit Implementation

public interface IUser2
    {
        void Display();
    }

    public class User1 : IUser2
    {     
        public void Display()
        {
            throw new NotImplementedException();
        }
    }

main ()
{
User1 obj = new User1();
obj.Display();
//Does compile successfully but should be avoided.

//Instead below code should be use
IUser2 obj = new User1();
obj.Display();
}

Conclusion about Explicit interfaces

  • Explicit interface should be avoided and ISP should be followed. In other words have different interfaces for different abstractions.
  • Explicit interfaces cannot be usedby the derived classes.
  • The only time it should be used when for reasons you want to implement the interface but the hide some methods and show methods via the class.

No comments:

Followers

Link