I ended up with something like the following code in a project I’m working on. I thought it was really odd that I was allowed to do it, but now I’m starting wonder what is most likely an architectural gaff on my part led me to this.
My questions to you are:
- What exactly is this called?
- What are some real world uses of this?
- Why would anyone want to do this?
Here are my Interfaces:
namespace ThisAndThat { public interface ICanDoThis { string Do(); } public interface ICanDoThat { string Do(); } public interface ICanDoThisAndThat : ICanDoThis, ICanDoThat { new string Do(); } }
Here’s my concrete class:
namespace ThisAndThat { public class CanDoThisAndThat : ICanDoThisAndThat { public string Do() { return 'I Can Do This And That!'; } string ICanDoThis.Do() { return 'I Can Do This!'; } string ICanDoThat.Do() { return 'I Can Do That!'; } } }
And my passing tests:
using Xunit; namespace ThisAndThat.Tests { public class ThisAndThatTests { [Fact] public void I_Can_Do_This_And_That() { ICanDoThisAndThat sut = new CanDoThisAndThat(); Assert.Equal('I Can Do This And That!', sut.Do()); } [Fact] public void I_Can_Do_This() { ICanDoThis sut = new CanDoThisAndThat(); Assert.Equal('I Can Do This!', sut.Do()); } [Fact] public void I_Can_Do_That() { ICanDoThat sut = new CanDoThisAndThat(); Assert.Equal('I Can Do That!', sut.Do()); } } }
There is absolutely nothing wrong with this code (provided it isn’t confusing for your users), and it isn’t a pattern with any name that I’m familiar with.
CanDoThisAndThatimplements two interfaces, so clients can use it in either way..NET allows interfaces to be implemented this way — known as explicit interface implementation.
Explicit interface implementation is useful when:
An example of case 2 from the .NET framework is
ICollection.SyncLock.List<T>implementsICollectionyet the following code will not compile because the member has intentionally been ‘hidden’ as the designers of the BCL no longer advocate locking collections in this way:Any legacy code of this format will still work, because the reference is of type
ICollectionexplicitly: