How to do component and interface-based programming in .Net

COM developers will be glad to see that they can use interfaces in .Net to their advatange, much as they used them in COM. For example, the code below works exactly the way you would think:

interface IA
{
  void a1();
  void a2();
}

class A : IA
{
  public void a1(){...}
  public void a2(){...}
}

IA myA = new A();
myA.a1();

This should make COM developers happy. What may make them unhappy is that this works too:

A myA = new A();
myA.a1();

With this code, the component oriented programming model has been left in the dust, and the client is using classic OO programming - against a class. COM developers need not despair, because structuring their service class (A) like this will force clients to use interfaces, rather than classes

class A : IA
{
  void IA.a1(){...}
  void IA.a2(){...}
}

With the service object coded like this, with the code A myA = new A() , myA cannot be used to invoke the methods in IA, and thus interface-based programming is enforced.

If you intend to use compnent programming techniques in your .Net projects, it's best to put interfaces into a separate assembly that contains only interfaces. This is useful because it completely decouples clients and servers from the interface, and allows conccurent development of both (and perhaps multiple clients and servers) once the interfaces have been agreed on.

COM programmers may wonder if QueryInterface can map into the .Net framework? The answer is that it does: as the 'as' keyword. For example, suppose my class implements 2 interfaces IA and IB:

class A : IA, IB {...}

If I have a reference to an IA type, and I want to see if it supports IB, I simply write this:>

IA myIA = new A();
IB myIB = myIA as IB; // like a QI
if (myIB != null)
{
  // It implements IB
}
else
{
  // It does not implement IB
}

As you can see, 'as' is semantically equivalent to QI.