gabsferreira
gabsferreira

Reputation: 3147

Why would an interface implement another interface?

I was looking at the declaration of List<T> and saw that it implements IList<T>, ICollection<T> and IEnumerable<T>(among others).

Then I went to look the definition of IList<T> and saw that it implements ICollection<T> and IEnumerable<T>.

What's the point of an interface implementing another interface if they work just as "contracts" and we write no real code at them?

Is this implementation cumulative? If it is, since IList<T> implements ICollection<T> and IEnumerable<T>, List<T> shouldn't implement only IList<T>?

Sorry if my question is confusing, I'm a litte bit puzzled right now.

Upvotes: 15

Views: 2933

Answers (2)

Dave Cousineau
Dave Cousineau

Reputation: 13218

At the very least it reduces redundancy.

public interface INamedObject { string Name { get; } }
public interface IValuedObject<T> { T Value { get; } }
public interface INamedValuedObject<T> : INamedObject, IValuedObject<T> { }

Is better design than:

public interface INamedObject { string Name { get; } }
public interface IValuedObject<T> { T Value { get; } }
public interface INamedValuedObject<T> {
   string Name { get; }
   T Value { get; }
}

Also, in the latter case, notice that an INamedValuedObject<T> is now neither an INamedObject nor an IValuedObject<T>.

You can read the former case as "Something that is an INamedValuedObject<T> is something that is an INamedObject, an IValuedObject<T>, and also has the following elements".

Upvotes: 9

Pat Hensel
Pat Hensel

Reputation: 1384

What's the point of an interface implementing another interface if they work just as "contracts" and we write no real code at them?

Interfaces support inheritance and facilitate polymorphism in the same way that classes do. An IList<T> is also an ICollection<T>, in the same way that a TextBox is a Control.

Is this implementation cumulative? If it is, since IList implements ICollection and IEnumerable, List shouldn't implement only IList?

As others have pointed out, this is mostly for readability and maintainability. Yes, inheritance is cumulative. But, when a class implements multiple interfaces that contain members with the same signature, it only needs to define one member for all implementations. Explicit interface implementation may be used to explicitly define a member for a given implementation.

Upvotes: 20

Related Questions