Other Required Changes
If you compare our C# code with the C++ code in the original command pattern article, you’ll notice that a few other changes were required to bring this code into the C# world.
Destructors
You may have noticed that no destructors were defined in Listing 2. I purposely removed them because this is how it’s done on .NET. In C# programming, you never have to destroy a managed object explicitly—this job is handled by the .NET garbage collector. Once an object goes out of scope, it becomes a candidate for garbage collection. The same mechanism exists in Java and Visual Basic.
What About Pointers to Classes?
C# won’t allow you take the address of a class object. This is because C# is a managed language and the address of an object is susceptible to sudden change thanks to the garbage collector. You can take the address of data types, but not entire classes. However, you’re allowed to take the address of a class member via the fixed keyword.
For the code in this article, we can avoid the need for such pointers by migrating to the use of C# references. The parameter in Listing 4 illustrates this principle in action.
Listing 4 Using C# references instead of C++ pointers.
public deleteNetworkObject(LspConnection lsp) { connection = lsp; }
Compare that to the original C++ signature for this method, shown in Listing 5.
Listing 5 The original C++ method.
deleteNetworkObject::deleteNetworkObject(LspConnection* lsp) { connection = lsp; }
The ported code in Listing 4 avoids the need for taking the address of a class (in this case, the LspConnection class).
It’s time to see the ported code working.