Implicit vs. explicit interface implementation Pattern

18 בJuly 2014

תגובה אחת

#we have actually to kinds of Interface Implementation in c

.What we called Implicit and Explicit

:To be clear, on this Interface

interface IDemo

    {

         int ID { get; set; }

    }

:We can implement

class ImplicitDemo : IDemo

    {

        private int _id;

        public int ID

        {

            get

            {

                return _id;

            }

            set

            {

                _id = value;

            }

        }

    }

:And :

class ExplicitDemo : IDemo

    {

        private int _id;


        int IDemo.ID

        {

            get

            {

                return _id;

            }

            set

            {

                _id = value;

            }

        }

    }

?First what will be the technic different

:While trying to invoke those classes it will be

class Program

    {

        static void Main(string[] args)

        {

 

            ImplicitDemo imp = new ImplicitDemo(){ID = 34};

        }

    }

:This is ok, but :

class Program

    {

        static void Main(string[] args)

        {

 

            ExplicitDemo exp = new ExplicitDemo(){ID = 45};

        }

    }

!Will not compile

:The only way to make it work is by some kind of casting like

ExplicitDemo exp = new ExplicitDemo();


exp as IDemo).ID = 45;


So, I might say that Explicit interface implementation is more Interface Oriented and expose our

.Interface Structure the object clients and it could be unsafe and may be overwrite

In other side, it is very nice to hide some details from the client if needed

:let’s follow this

interface IDemo

    {

         void Action();

    }

?In general Interface members implementation must be public right

class ImplicitDemo : IDemo

    {

       public  void Action()

        {

        }

    }

Well not so accurate, using explicit Implementation allow us to declare some private members and

!get more flexible design

class ExplicitDemo : IDemo

    {

       private void IDemo.Action()

        {

        }

    }

but, remember to use this explicit function only possible outside of the class and by cast to the

.Interface type

:Tip

Sometime when facing multiple Interface inheritance with name conflicts, also when BaseClass itself

.provide implementation Explicit usage may found reasonable

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

תגובה אחת

  1. dor cohen20 בNovember 2016 ב 13:01

    Thank you for helping out, excellent info. “Nobody can be exactly like me. Sometimes even I have trouble doing it.” by Tallulah Bankhead.

    Reply