Why is a base class in C# allowed to implement an interface contract without inheriting from it?

StackOverflow https://stackoverflow.com/questions/2942772

  •  05-10-2019
  •  | 
  •  

سؤال

I've stumbled upon this "feature" of C# - the base class that implements interface methods does not have to derive from it.

Example:

public interface IContract
{
    void Func();
}

// Note that Base does **not** derive from IContract
public abstract class Base
{
    public void Func()
    {
        Console.WriteLine("Base.Func");
    }
}

// Note that Derived does *not* provide implementation for IContract
public class Derived : Base, IContract
{
}

What happens is that Derived magically picks-up a public method, Base.Func, and decides that it will implement IContract.Func.

What is the reason behind this magic?

IMHO: this "quasi-implementation" feature is very-unintuitive and make code-inspection much harder. What do you think?

هل كانت مفيدة؟

المحلول

The reason is that your comment is simply incorrect:

// Note that Derived does not provide implementation for IContract

Sure it does. Follow the logic through.

  • Derived is required to provide a public member corresponding to each member of IContract.
  • All inheritable members of a base class are also members of a derived class; that's the definition of inheritance.
  • Therefore Derived provides an implementation for IContract; its inherited member is a member that fulfills the requirement
  • Therefore, no error.

this feature is very-unintuitive and make code-inspection much harder. What do you think?

I think you shouldn't use the feature if you don't like it. If you find it confusing and weird to read code that uses this feature then encourage your coworkers who use this feature to stop doing so.

How is this feature different from any other feature where a method from a base class is used from a derived class? There are a number of different ways in which a method from a base class may be used or mentioned in a derived class -- method calls, overrides, method group conversions, and so on.

Furthermore, this is relatively speaking a simple, straightforward case. If you really want to complain about confusing interface semantics in C#, I'd spend my time complaining about interface reimplementation semantics. That's the one that really seems to bake people's noodles. I always have to look that thing up in the spec to make sure I'm getting the semantics right.

نصائح أخرى

Why do you think that this is strange and unnatural? Every public member of base class is also a public member of derived class. So there is no contradiction here. Anyhow you can implement interface explicitely if you like.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top