Many of the language enhancements we have looked at so far can greatly ease working with legacy code such as COM objects.
Let's look in more detail by adapting an example from Scott Hansleman's blog (www.hanselman.com/blog/CLRAndDLRAndBCLOhMyWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx).
In Scott's example, the Microsoft Office API is used to open an existing text file. To see this example, add the following code and a reference to Microsoft.Office.Interop.Word, and then take a look at the IntelliSense for the Open() method (see Figure 3-1):
using Microsoft.Office.Interop.Word; var WordApplication = new Microsoft.Office.Interop.Word.Application(); WordApplication.Visible = true; object missing = System.Reflection.Missing.Value; object file =@"c: est.txt"; object visible = true; object readOnly = false; Document aDoc = WordApplication.Documents.Open( ref file,ref missing,ref readOnly,ref missing, ref missing,ref missing,ref missing,ref missing, ref missing,ref missing,ref missing,ref visible, ref missing,ref missing,ref missing,ref missing);
.NET optional and named parameters make this much easier:
var betterWay = WordApplication.Documents.Open(file, ReadOnly: true, Visible: true); betterWay.Activate();
The new dynamic functionality (which we will look at shortly) can also make your code more readable by allowing you to infer many casting operations. For example, the compiler can now work out the type of object you are using (duck typing), allowing code such as
((Excel.Range) excel.Cells[1, 1]).Value2 = "Excell-ent!";
to be rewritten as
excel.Cells[1, 1].Value = "Excell-ent!";
It may not be very different, but it's much more readable.
Another COM-related change worth mentioning is that you no longer need PIA (Primary Interop Assembly) files. In previous versions of Visual Studio, when a COM component was referenced, Visual Studio would create a PIA, an additional assembly to describe the COM DLL to the CLR.
Unfortunately, these PIA files could get pretty large, as they described every method of the COM object (including methods you weren't using). In VS2010, to stop Visual Studio from generating PIA files, simply set the Embed Interop Types property to True in Solution Explorer.
18.219.45.88