If a class implements an interface from two separate interfaces, does it behave exactly as if it implements it only once?
Example:
public interface IAnimal { /* ... */ }
public interface IFullAnimal : IAnimal { /* ... */ }
public interface IBear : IAnimal { /* ... */ }
public interface IFullBear : IBear, IFullAnimal { /* ... */ }
// and implementing IFullBear:
public class FullBear : IFullBear { /* ... */ }
Above, FullBear
implements IAnimal
from both IFullAnimal
and IBear
through IFullBear
. Does this introduce any weird behavior concerning the implementation of IAnimal since both IFullAnimal
and IBear
do not provide any information about the implementation of IAnimal
(as the language does not allow that).
No, and this is a very common and harmless scenario. System.Collections.Generic
namespace is a great example of similar "redundant" interface declarations:
public class List<T> : IList<T>,
System.Collections.IList,
IReadOnlyList<T>
Both IList<T>
and IReadOnlyList<T>
evidently implement IEnumerable<T>
and the world hasn't ended.
Don't confuse this with interface reimplementation, which does change behavior:
interface IFoo
{
void Foo();
}
class Base: IFoo
{
public void Foo() { Console.WriteLine("Base Foo!");
}
class Derived: Base { }
class DerivedWithATwist: Base, IFoo //redeclares interface
{
void IFoo.Foo() { Console.WriteLine("Derived Foo!");
}
And now,
IFoo foo = new Base();
IFoo derived = new Derived();
IFoo derivedWithATwist = new DerivedWithATwist();
foo.Foo(); //Base Foo!
derived.Foo(); //Base Foo!
derivedWithATwist.Foo(); //Derived Foo!
(derivedWithATwist as Base).Foo(); //Base Foo! !!!