Monday, November 08, 2004

Interfaces - benfits and platform differences

Interfaces is a very powerful tool that can improve the quality of your code, if used properly. Interfaces can give the following benefits:

  • Reduced coupling between components
  • Strong encapsulation
  • High extensibility
  • Easy substitutability
  • Run-time discovery of object capabilities

Under the hood, interfaces are implemented very differently in .NET and Win32. Win32 interfaces follow the COM model, with an IUknown base interface that provides basic services for reference counted lifetimes and interface support querying.

A Win32 interface declaration needs a GUID to enable as-casts (or QueryInterface or Supports calls). GUIDs are not needed in .NET - they can optionally be used to expose interfaces to COM with a specific GUID. To generate a GUID in the editor use the Shift+Ctrl+G keyboard shortcut.

IMyInterface = interface
procedure Foo;

.NET interfaces do away with reference counting and instead relies on the garbage collection mechanism that all object references enjoy. There is no base-interface that all other interfaces inherit from.

Instead of QueryInterface, IL instructions like castclass and isclass and methods of the Type class are used. At runtime, the reference value of an interface variable is identical to the object reference value that implements the interface. The only difference is the type of the variable and how the JIT compiler dispatches method calls on the interface reference. More on casting to and from interfaces differences shortly.

No comments:

Copyright © 2004-2007 by Hallvard Vassbotn