Friday 27 April 2012

C#: Interfaces - Implicit and Explicit implementation


mplicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implememnted as:
        public void CopyTo(Array array, int index)
        {
                throw new NotImplementedException();
        }
and explicity as:
        void ICollection.CopyTo(Array array, int index)
        {
                throw new NotImplementedException();
        }
The difference being that implicitly is accessible throuh your class you created when it is cast as that class as well as when its cast as the interface. Explicit implentation allows it to only be accessible when cast as the interface itself.
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when i need two implemetations. But regardless i rarely use it.
I am sure there are more reasons to use it/not use it that others will post

No comments:

Post a Comment