Home > .NET Framework > Explicit Interface Implementation

Explicit Interface Implementation

Why do you need explicit interface implmenation?
1. Prevent the external "interface" of the class from being polluted with interface implementations. In other words, to avoid seeing long method lists when you press a "." in VS.NET
2. Avoid name collision when there more than one of the interfaces being implemented have a method with exactly the same signature.
3. Simulate covariant return types. Allow overrides in derived classes which return a derived type instead of a base type.
Ex: IEnmerable.GetEnumerator implementations, where the generic object returning version is hidden, in preference to the type specific version.
4. When you have to implement a public class, and you have to implement an interface in that class that is ‘internal’.
 
Design Guidelines (from Brad Abrams)
 
  • Do not use explicit members as a security boundary. They can be called by any client who cast an instance to the interface
  • Do use explicit members to hide implementation details (Option 4)
  • Do use explicit members to approximate private interface implementations.  If you need to implement an interface for only infrastructure reasons and you NEVER expect developers to directly call methods on that interface from this type then implement the members explicitly to “hide” them from public view. Ex: IConvertible implemenation in the base CLR data types. (Option 1)
  • Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override
    public class FixedBase : ITest
    {
        void ITest.SomeMethod()
        {
            SomeMethod();
        }
 
        virtual protected void SomeMethod()
        {
            // …
        }
    }
    public class Derived : FixedBase, ITest
    {
        override protected void SomeMethod()
        {
            // …
            base.SomeMethod();
            // This would cause recursion and a stack overflow.
            // ((ITest)this).SomeMethod();
        }
    }
 
Compiled From:
Advertisements
Categories: .NET Framework
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: