Click here to Skip to main content
13,627,794 members
Click here to Skip to main content
Add your own
alternative version

Stats

60.3K views
31 bookmarked
Posted 12 Jun 2015
Licenced CPOL

Explicit Interface VS Implicit Interface in C#?

, 12 Jun 2015
Rate this:
Please Sign up or sign in to vote.
In this article we will discuss about explicit interfaces, how they differ from implicit interface and why they should be avoided.

Contents

Introduction

What are Explicit and Implicit Interfaces?

When do we need Explicit Interface ?

More clean approach: - ISP ( Interface segregation principle )

Child classes have no access to explicitly implemented interface.

Makes code more unreadable

Hide non-preferred Interface members

Myth about Explicit Interfaces

Conclusion about Explicit interfaces

Introduction

In this article we will discuss about explicit interfaces, how they differ from implicit interface and why they should be avoided.

What are Explicit and Implicit Interfaces?

There are two ways of implementing C# interfaces “Explicit” and “Implicit”.

When you implicitly implement an interface below is how the code looks like. “IDal” is the interface and “Add” and “Update” are the methods implemented implicitly. Most of the developers implement interface implicitly.

public class Person : IDal
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public void Add()
        {
            throw new NotImplementedException();
        }

        public void Update()
        {
            throw new NotImplementedException();
        }
}

If you explicitly implement an interface below is how the code looks like. The difference is that the “Add” and “Update” methods are now private.

public class Person : IDal
{
        public string FirstName { get; set; }
        public string LastName { get; set; }


void IDal.Add()
        {
            throw new NotImplementedException();
        }

        void IDal.Update()
        {
            throw new NotImplementedException();
        }
}

In simple words the difference between “Implicit” interface and “Explicit” interface is that in implicit the interface methods are publicly implemented while in explicit the methods are privatelyimplemented.

So the next question which arises iswhy do we have this difference of public vs private and whenshouldwe use “Implicit” interfaceVS “Explicit” interface.

When do we need Explicit Interface ?

Let me make a statement here:-

“Explicit” interface should be used when your concrete class abstraction does not include the interface abstraction. It’s a quick and dirty way to achieve dual abstraction.

I can sense how tough it is to understand the above statement.

Let’s go slow and nice, first let’s understand the word “Abstraction”.

“Abstraction” means show only the necessarymethods/properties of your class from the perspective of the client.

In case you are new to this word abstraction I would encourage you to see this C# Youtube Abstraction video.

Below is a simple “Person” class with some properties and methods.

public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public void Add()
        {

        }

        public void Update()
        {

        }
    }

Now this “Person” class a.k.a library is consumed by two client’s

“PersonalInformation” and “DataAccessBatchProcess”.

“PersonalInformation” is a simple UI application via which “Person” information and “DataBatchProcess” is a simple batch process which adds this data to the database.

In this case “Person” is the library and “DataAccessBatchProcess” and “PersonalInformation” applications are consumers of the library.

Let me make a statement about best practices.

One of the signs of a good software architecture is you will see lot of respect for “Abstraction” as per client profile.

In this particular scenario the “Personal Information” application would like to only see “FirstName” and “LastName” while the data access batch process would like to only see “Add” and “Update” methods. Putting in other words we have two different kind of abstraction for the same class.

A good architecture reacts to changes in a graceful manner. In a good architecture when any change request is executed least number of code changes should happen.

Least number of code changes can only happen when abstraction is implemented in proper way.

Because due to abstraction only necessary things are seen to the respective consumer and unnecessary / unconnected changes in a system do not affect them.

So the first step is to create an Dal interface which only has “Add” and “Update” method.

public interface IDal
{
        void Add();
        void Update();
}

We then implement the “IDal” interface implicitly.

public class Person : IDal
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public void Add()
        {
        // Here goes the data access layer add code
        }

        public void Update()
        {
// Here goes the data access layer update code
        }
    }

So now when we look at the “Person” class from interface “IDal” lens we just see “Add” and “Update” methods. For the data access layer batch process it does not matter what business object is at the back ground.

It can be any type of business object person,customer,account – what matters for him is “Update” and “Add” methods.

But now let’s test if the abstraction of “Personal Information” application is respected or not.

You can see when we create the object of “Person” class , we also see “Update” and “Add” methods. In other words the “Personal Information” application is seeing unnecessary things.

So if tomorrow any changes are done to “Update” and “Add” methods they should not affect “Personal Information” application unnecessarily.

One of the sign of bad architecture is when a change request is executed and unrelated section changes.

So the QUICK DIRTY WAY to fix this by using “Explicit” interfaces. Please note “Quick Dirty way”word is highlighted and will talk about the same soon.

So if we implement the “IDal” interface “Explicity” below is how the code looks like.

Most important point to note “Add” and “Update” methods have become private.
public class Person : IDal
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        void IDal.Add()
        {
            // Add code goes here
        }

        void IDal.Update()
        {
            // Update code goes here.
        }
    }

Now if we create the “Person” object we do not see “Update” and “Add” method and we are respecting the abstraction of “Personal Information” application.

Just to summarize mathematicallyJJ

Class public Members=( Class Public Members+Implicit Interface Members) - Explicit Interface Members

More clean approach: - ISP ( Interface segregation principle )

The above approach is a quick and dirty way of implementing multiple abstractions for a class. Explicit interface should be avoided as far as possible.

The proper way is to follow SOLID principle and implement ISP( Interface segregation principle). In case new to SOLID principle read this article SOLID Principles using C#.

So create two different interfaces one for Dal and one for person and the respective abstraction would be more clean.

Child classes have no access to explicitly implemented interface.

If you are implementing an interface explicitly the members become private and your child classes do not have the ability to override the members and thus the complete inheritance hierarchy is broken.

In the below example my “Person” class is inherited by “Employee”. But because the interface is implemented explicitly , “Add()” and “Update()” became private and with that I loose the benefit of chained polymorphism.

public class Person : IDal
{

        void IDal.Add()
        {
            throw new NotImplementedException();
        }
        void IDal.Update()
        {
            throw new NotImplementedException();
        }
}

public class Employee : Person
{

}

Makes code more unreadable

The whole point of interfaces is that it is a contract. A contract between two classes. Developers for years have known that contracts are normally public. But in this case suddenly the interface method becomes private so this also can lead to confusion in terms of readability.

Hide non-preferred Interface members

The only time I feel the need to explicit interface when I want to make some methods private and some methods public of the implemented interface.

For example in the below class I am implementing “IEnumerable” interface in that I want to client to access “GetEnumerator” but not the “Enumerable”.

public class Person : IEnumerable<string>
    {


public IEnumerator<string> GetEnumerator()
        {
throw new NotImplementedException();
        }

System.Collections.IEnumeratorSystem.Collections.IEnumerable.GetEnumerator()
        {
throw new NotImplementedException();
        }
    }

Myth about Explicit Interfaces

One of the myths about explicit interface is that, it should be used when you want to implement same method names from different interfaces.

Watch this video to understand what I mean same method name from different interfaces https://www.youtube.com/watch?v=6ZxVx93wa7Q.

If you ever land in such kind of a scenario it’s only because of bad design. I do not see this as a compelling factor for explicit interfaces.

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.

I do understand I have made a very rude conclusion about explicit interfaces. I would like to hear from the community, get feedback and improve.

Please do provide your comment in the comment section below.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
BugA caveat with comparison to the private accessor Pin
shivku.goku19-Dec-17 19:24
professionalshivku.goku19-Dec-17 19:24 
PraiseSuperb Explanation Pin
kksaryan12-Nov-17 19:11
memberkksaryan12-Nov-17 19:11 
QuestionGood article! Pin
Member 1232607813-Feb-16 23:14
memberMember 1232607813-Feb-16 23:14 
GeneralSome comments Pin
Paulo Zemek25-Jun-15 10:52
mvpPaulo Zemek25-Jun-15 10:52 
GeneralRe: Some comments Pin
Shivprasad koirala28-Jun-15 19:11
mvpShivprasad koirala28-Jun-15 19:11 
QuestionMy vote of 4 Pin
dmjm-h15-Jun-15 20:05
memberdmjm-h15-Jun-15 20:05 
GeneralMy vote of 2 Pin
hoangcute9x15-Jun-15 15:57
professionalhoangcute9x15-Jun-15 15:57 
GeneralRe: My vote of 2 Pin
Shivprasad koirala15-Jun-15 15:59
mvpShivprasad koirala15-Jun-15 15:59 
QuestionSorry! I am also not convinced. Pin
Member 32435415-Jun-15 10:08
memberMember 32435415-Jun-15 10:08 
AnswerRe: Sorry! I am also not convinced. Pin
Shivprasad koirala15-Jun-15 20:34
mvpShivprasad koirala15-Jun-15 20:34 
QuestionSorry! I am not convinced! Pin
debiprasadghosh14-Jun-15 22:27
memberdebiprasadghosh14-Jun-15 22:27 
AnswerRe: Sorry! I am not convinced! Pin
Shivprasad koirala14-Jun-15 23:53
mvpShivprasad koirala14-Jun-15 23:53 
QuestionFalse argument Pin
PaulLinton14-Jun-15 20:34
memberPaulLinton14-Jun-15 20:34 
AnswerRe: False argument Pin
Shivprasad koirala14-Jun-15 23:53
mvpShivprasad koirala14-Jun-15 23:53 
GeneralRe: False argument Pin
debiprasadghosh15-Jun-15 1:59
memberdebiprasadghosh15-Jun-15 1:59 
GeneralRe: False argument Pin
Shivprasad koirala15-Jun-15 2:47
mvpShivprasad koirala15-Jun-15 2:47 
NewsCreate Pin
Member 1176188112-Jun-15 21:47
memberMember 1176188112-Jun-15 21:47 
GeneralGood article Pin
vinod.jangle12-Jun-15 12:53
membervinod.jangle12-Jun-15 12:53 
QuestionGreat Concept explained in the most simple Way. Pin
Mahendra_Nepali12-Jun-15 4:16
memberMahendra_Nepali12-Jun-15 4:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.180712.1 | Last Updated 12 Jun 2015
Article Copyright 2015 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid