Search code examples
c#.netoopinheritanceabstraction

Strange inheritance modification


I'm a .NET developer and know pretty much about OOP. However, recently I noticed one interesting fact.

System.Data.SqlClient.SqlCommand derives from System.Data.Common.DbCommand. The latter implements System.IDbCommand. System.IDbCommand exposes the property Connection which an instance of IDbConnection. In DbCommand However this property returns DbConnection type. And finally the same property in SqlCommand is of type SqlConnection

I've tried to perform the same however it gave a compile time error. How was this achieved in above example and how can I recreate the same pattern?

My code (not compiling):

public interface IFoo { }
public interface IBar 
{
   IFoo TheFoo();
}

public abstract class AbsFoo : IFoo { }
public abstract class AbsBar : IBar 
{
    public abstract AbsFoo TheFoo();
}

public class ConcreteFoo : AbsFoo { }
public class ConcreteBar : AbsBar { }

Solution

  • Explicit interface implementation is the name of the game here. Try this:

    public abstract class AbsBar : IBar {
        IFoo IFoo.TheFoo() { return this.TheFoo(); }
        public abstract AbsFoo TheFoo();
    }
    

    Here's a good guide on implicit vs. explicit implementation.