Separating Interface from Implementation

In both C# and Visual Basic 2005, the reserved word interface defines a CLR reference type that can’t have any implementation, can’t be instantiated, and has only public members. Saying that an interface can’t have implementation means that it’s as if all the interface’s methods and properties were abstract. Saying it can’t be instantiated means the same as if the interface were an abstract class (or MustInherit in Visual Basic 2005). For example, this interface definition:

    public interface IMyInterface
    {
       void Method1();
       void Method2();
       void Method3();
    }

is almost equivalent to this class definition:

    public abstract class MyInterface
    {
       public abstract void Method1();
       public abstract void Method2();
       public abstract void Method3();
    }

In traditional object-oriented programming, you typically use an abstract class to define a service abstraction. The abstract class serves to define a set of signatures that multiple classes will implement after deriving from the abstract class. When different service providers share a common base class, they all become polymorphic with that service abstraction, and the client can potentially switch between providers with minimum changes. There are a few important differences between an abstract class and an interface:

  • An abstract class can still have implementation: it can have member variables or non-abstract methods or properties. An interface can’t have implementation or member variables.

  • A .NET class can derive ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.