Free mag vol1 | Page 674

CHAPTER 16  DYNAMIC TYPES AND THE DYNAMIC LANGUAGE RUNTIME On a related note, many COM methods provided support for named arguments, which as you recall from Chapter 4, allows you to pass values to members in any order you require. Given that C# supports this same feature, it is very simply to “skip” over a set of optional arguments you don’t care about, and only set the few you do. Another common COM interop pain point has to do with the fact that many COM methods were designed to take and return a very particular data type, termed the Variant. Much like the C# dynamic keyword, a Variant data type could be assigned to any type of COM data on the fly (strings, interface references, numerical values, etc.). Before you had the dynamic keyword, passing or receiving Variant data points required some hoop jumping, typically by way of numerous casting operations. When you set the Embed Interop Types property to True, all COM Variant types are automatically mapped to dynamic data. This will not only reduce the need to extraneous casting operations when working with underlying COM Variant data types, but will also further hide some COM complexities, such as working with COM indexers. To showcase how the use of C# optional arguments, named arguments, and the dynamic keyword all work together to simplify COM interop, you will now build an application that makes use of the Microsoft Office object model. As you work through the example, you will get a chance to make use of the new features, as well as forgo them, and then compare and contrast the workload.  Note If you do not have a background in Windows Forms, you might wish to simply load the completed solution into Visual Studio and experiment with the code, rather than build this application by hand. COM Interop Using C# Dynamic Data Assume you have a Windows Form GUI application (named ExportDataToOfficeApp), whose main window hosts a DataGridView control named dataGridCars. This same window has two Button controls, the first of which will bring up a custom dialog box to insert a new row of data to the grid, and the other of which will export the grid’s data to an Excel spreadsheet. Figure 16-9 shows the completed GUI. Figure 16-9.The GUI of the COM interop example 616