Developing .NET Components
To create a .NET
component in C# (or any other .NET Language), you simply declare a
class. When the class is instantiated by the CLR, the result is a
binary component. Example C-1 shows a simple class
named MyClass
that implements the
IMessage
interface and displays a message box with
the word “Hello” when the interface’s
ShowMessage( )
method is called.
Example C-1. Building a component in .NET
namespace MyNamespace { using System; using System.Windows.Forms; public interface IMessage { void ShowMessage( ); } public class MyComponent :IMessage { public MyComponent(){}//constructor ~ MyComponent(){}//destructor public void ShowMessage( ) { MessageBox.Show("Hello!","MyComponent"); } } }
The MyComponent
class in Example C-1 is defined as public
,
making it accessible to any .NET or COM client once you export the
component to COM. You can define a class constructor to do object
initialization, as in this example, but the destructor has different
semantics than the classic C++ destructor because .NET uses
nondeterministic object finalization. You can implement other methods
to do object cleanup as well. The implementation of
ShowMessage( )
uses the static Show( )
method of the MessageBox
class. Like
in C++, C# allows you to call a class (static) method without
instantiating an object first.
Example C-1 demonstrates a few additional key points regarding developing .NET components: using namespaces and interface-based programming. These points are discussed next. ...
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.