C++ to C# Migration
Each new technology brings its own merits to the table, and Microsoft’s .NET is no exception. As programmers, we must strive to develop solutions that use the advantages of the new technologies while avoiding binding ourselves too closely to them. In the same way as building construction has been described as "frozen music," there’s a similar phenomenon in relationship to programming languages. Once you express a solution in a given programming language, very often you’re inextricably tied to that language. Anyone who has ported code from one language or environment to another knows this fact all too well.
Let’s assume that you have an important block of legacy C++ code that you want to migrate into C#. To make the process of migration a little more realistic, I’ll take a piece of C++ code I wrote as part of my article "C++ Command Pattern for Network Operations," and show you how to migrate (port) that code into C#. The C++ code in this case is an expression of the command design pattern.
Since I discussed the advantages of command patterns in my article on that topic, I won’t dwell on this aspect. The important issue for the present context is that the command pattern is just as applicable in C# as it is in the C++ domain. This forms at least one rationale for going to the bother of migrating the C++ code!
I used the excellent open source SharpDevelop integrated development environment (IDE) for the code in this project. But you can use any tool you like; for example, Visual Studio or even the command line.
Listing 1 shows a sneak preview of the ported C# code, where:
- I create a network object.
- I create a deletion (command pattern) object.
- I delete the network object.
Listing 1 Implementation of the command pattern.
LspConnection* lsp = new LspConnection(1, 0, 1); deleteNetworkObject* deleteObject = new deleteNetworkObject(lsp); deleteObject->Execute();
As Listing 1 shows, there are two distinct objects: the application entity and a delete command-entity. Structuring your classes in this way provides flexibility and reusability.