Sunday, June 28, 2026

C# Example of Interface Hierarchy, Name conflict and Explicit Interface Implementation

Example of Interface Hierarchy
interface IWalkable
{
    void Walk();
}
interface IFlyable
{
    void Walk();
    void Fly();
}
interface IConflictable : IWalkable, IFlyable
{
    void GetNature();
}

class Animal : IConflictable
{
    void IFlyable.Fly()
    {
        Console.WriteLine("Bird can fly.");
    }

    void IConflictable.GetNature()
    {
        Console.WriteLine("Nature of cat and bird.");
    }

    void IWalkable.Walk()
    {
        Console.WriteLine("Cat can walk.");
    }

    void IFlyable.Walk()
    {
        Console.WriteLine("Bird can walk.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        IConflictable animal = new Animal();
        animal.GetNature();
        animal.Fly();
        // animal.Walk(); // conflict because Walk in both IWalkable and IFlyable
        ((IWalkable)animal).Walk();
        ((IFlyable)animal).Walk();
    }
}
In above code, animal is declared as IConflictable.

IConflictable inherits both IWalkable and IFlyable, and both interfaces contain a Walk() method. Because of that, calling: animal.Walk(); is ambiguous — the compiler doesn't know whether you mean IWalkable.Walk() or IFlyable.Walk(). To resolve this issue, Explicit Interface Implementation is required. Therefore, both Walk() methods are implemented explicitly.

Then to call desired Walk() method, we must cast to the desired interface.

To call IFlyable.Walk():
IConflictable animal = new Animal();
((IFlyable)animal).Walk(); // Output: Bird can walk.
To call IWalkable.Walk():
IConflictable animal = new Animal();
((IWalkable)animal).Walk(); // Output: Cat can walk.

No comments:

Post a Comment

Hot Topics