I am a bit unclear on the syntax of inheritance for interfaces in C#.
For example:
public interface IFoo
{
}
public interface IBar : IFoo
{
}
What is the difference between this:
public interface IQux : IBar
{
}
and this:
public interface IQux : IBar, IFoo
{
}
Or, for a real world example, Why is ICollection<T>
declared like this:
public interface ICollection<T> : IEnumerable<T>, IEnumerable
instead of this:
public interface ICollection<T> : IEnumerable<T>
given that IEnumerable<T>
already inherits from IEnumerable
?
But unlike classes, interfaces can actually inherit from multiple interfaces. This is done by listing the names of all interfaces to inherit from, separated by comma. A class implementing an interface which inherits from multiple interfaces must implement all methods from the interface and its parent interfaces.
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
Interface inheritance : An Interface can extend other interface. Inheritance is inheriting the properties of parent class into child class. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
Interface can contain declarations of method, properties, indexers, and events. Interface cannot include private, protected, or internal members. All the members are public by default. Interface cannot contain fields, and auto-implemented properties.
Eric Lippert explains it very well in this article:
https://blogs.msdn.microsoft.com/ericlippert/2011/04/04/so-many-interfaces
If IBar
inherits from IFoo
, then, from the compiler's perspective, there is no difference between:
public interface IQux : IBar
{
}
and this:
public interface IQux : IBar, IFoo
{
}
You can choose to state that IQux
incorporates IFoo
if you think it makes the code more readable. Or you can choose not to.
Generics didn't exist from the start -- look at the C# 1.0 docs and you won't see IEnumerable<T>.
Regarding the first question: there is no difference (not even with explicit interface implementations as far as I can tell).
Conside this:
public interface IFoo
{
void M();
}
public interface IBar : IFoo { }
public interface IQux : IBar, IFoo { }
public interface IQux2 : IBar { }
// Both work:
// class X : IQux
class X : IQux2
{
void IFoo.M() { }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With