Feb 15, 2010

The semantics of c# interface

We all use interface construct in c#. Recently I came across the Haack's blog Interface Inheritance Esoterica, I decided to find out more. So I write a very simple example like below

public interface IAnimal
    {
        void Walk();
    }

    public interface IBird : IAnimal
    {
        void Fly();
    }

    public class Bird : IBird 
    {
        void IBird.Fly()
        {
            throw new NotImplementedException();
        }

        void IAnimal.Walk()
        {
            throw new NotImplementedException();
        }
    }

Then I use ILDASM to examine the IL generated, the Bird class actually implement two interface,


//Bird IL
.class public auto ansi beforefieldinit DemoInterface.Bird
       extends [mscorlib]System.Object
       implements DemoInterface.IBird,
                  DemoInterface.IAnimal
{
} // end of class DemoInterface.Bird

//
.class interface public abstract auto ansi DemoInterface.IBird
       implements DemoInterface.IAnimal
{
} // end of class DemoInterface.IBird


We can see that the Walk is not a member of IBird, the semantics here is the class that implement IBird, should also implement IAnimal. So I change my code to be the following

public interface IAnimal
    {
        void Walk();
    }

    public interface IBird //: IAnimal
    {
        void Fly();
    }

    public class Bird : IBird , IAnimal
    {
        void IBird.Fly()
        {
            throw new NotImplementedException();
        }

        void IAnimal.Walk()
        {
            throw new NotImplementedException();
        }
    }

This time the generated IL for Bird is exactly the same as previous code. The only difference is that IBird does not "implement" IAniaml. In the first example, the semantics of Bird implementing IBird is as following


  1. The class is an IBird (or we can say it has gene.) Even the IBird interface has no member it still has semantics, System.Web.UI.INamingContainer it is an example.
  2. The Bird class is an IAnimal
  3. The Bird class implements IBird member Fly()
  4. IAniaml's member is not the member of IBird, but IBird support IAnimal's memeber
  5. The class that implements IBird, also need to implements IAnimal.
  6. The Bird class implements IAniaml member Walk(), because of previous semantics

The the original intention of interface is contract, and a contact can be a composite, which means a contract can be a combination of other contract(s).