Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

4.6 Interface Design

Although most APIs are best modeled using classes and structs, there are cases in which interfaces are more appropriate or are the only option.

The CLR does not support multiple inheritance (i.e., CLR classes cannot inherit from more than one base class), but it does allow types to implement one or more interfaces in addition to inheriting from a base class. Therefore interfaces are often used to achieve the effect of multiple inheritance. For example, IDisposable is an interface that allows types to support disposability independent of any other inheritance hierarchy in which they want to participate.

public class Component : MarshalByRefObject, IDisposable, IComponent {
 
}

The other situation in which defining an interface is appropriate is in creating a common interface that can be supported by several types including some value types. Value types cannot inherit from types other than System.ValueType, but they can implement interfaces, so using an interface is the only option to provide a common base type.

public struct Boolean : IComparable {
   
}
public class String: IComparable {
   
}

Except for the situations described in these guidelines, you should, in general, choose classes rather than interfaces in designing managed code reusable libraries.

  • + Share This
  • 🔖 Save To Your Account