Writing .NET Client-Side Code
All that a .NET client has to do to use a component is add a reference in its project setting to the assembly containing the component, create an object, and then use it:
using MyNamespace; //Interface-based programming: IMessage myObj; myObj = (IMessage)new MyComponent( ); myObj.ShowMessage( );
You usually do not use pointers in C#. Everything is referenced using
the dot (.)
operator. Note also that the client casts the newly created object to
the IMessage
interface. This is the .NET
equivalent of QueryInterface( )
. If the object
does not support the interface it is being cast to, an exception is
thrown.
The client can instead perform a controlled query for the interface
using the as
keyword. If the object does not
support the interface, the returned reference is
null
:
using MyNamespace;
//Even better: check for type mismatch
IMessage myObj;
myObj = new MyComponent( ) as
IMessage;
Debug.Assert(myObj!= null);
myObj.ShowMessage( );
As mentioned before, .NET does not enforce separation of interface from implementation, so the client could create the object type directly:
using MyNamespace; //Avoid doing this: MyComponent myObj; myObj = new MyComponent( ); myObj.ShowMessage( );
However, you should avoid writing client code that way because doing so means that the client code is not polymorphic with other implementations of the same interface. Such client code also couples interacting modules. Imagine a situation in which Module 1 creates the object and ...
Get COM & .NET Component Services 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.