C Sharp

Summary

The last bit of information I'll leave you with is where these different mechanisms for working with legacy code-PInvoke, unsafecode, and COM Interop-fit into the overall scheme of things regarding .NET. In this chapter, you learned the following: -

  • With regards to using standard C-like function calls, you learned how to use PInvoke along with several attributes that make the issues of marshalling different types of data, including custom data, easier.
  • With regards to unsafecode, you learned how to forego the benefits of managed code within a C# application for situations in which you need to have more control. These scenarios might include times when you need to manually manipulate memory for efficiency's sake or when you're moving blocks of code into a C# application and simply aren't ready yet to convert that code to managed code.
  • With regards to COM, you saw how to expose Classic COM components to .NET applications and how COM Interop seamlessly allows you to reuse existing COM components from managed code. Then, you skimmed through ways to invoke your COM component by using both early bindingand late bindingalong with ways to do run-time type checking. Finally, you saw how managed threads declare their apartment affiliations when invoking COM components.

At this point, as a developer using one of these mechanisms for dealing with unmanaged code, you might be wondering whether it makes sense to continue using these methodologies or whether you should bite the bullet and transition directly into the .NET world by writing all your components and business logic code as managed components using a .NET language such as C#. I'll tell you that the answer depends on your current situation.

If you have tons of legacy code-whether it be C-like functions in DLLs, code that directly manipulates memory, COM components, or a combination of the three-the fact is that you're probably not going to be able to convert all your code overnight. In this case, it makes sense to leverage the different .NET mechanisms for working with legacy code. However, if you're writing new business logic code from scratch, I would most heartily advise you to write your code as managed components by using a language such as C#. That way, you can do away with the performance penalties that inevitably incur while transitioning between managed and unmanaged boundaries.