15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

a COM instance, and then use dynamic binding to call members from then on. Of<br />

course, there’s no IntelliSense, and compile-time checks are impossible:<br />

Type excelAppType = Type.GetTypeFromProgID ("Excel.Application", true);<br />

dynamic excel = Activator.CreateInstance (excelAppType);<br />

excel.Visible = true;<br />

dynamic wb = excel.Workbooks.Add();<br />

excel.Cells [1, 1].Value2 = "foo";<br />

(The same thing can be achieved, much more clumsily, with reflection instead of<br />

dynamic binding.)<br />

A variation of this theme is calling a COM component that supports<br />

only IDispatch. Such components are quite rare, however.<br />

Dynamic binding can also be useful (to a lesser extent) in dealing with the COM<br />

variant type. COM API functions are often peppered with this type, which is roughly<br />

equivalent to object in .NET. The runtime maps variant to object prior to C# 4.0,<br />

with the effect that you must explicitly cast return values—as in the following<br />

example:<br />

var excel = new Excel.Application();<br />

excel.Visible = true;<br />

Workbook workBook = excel.Workbooks.Add (System.Reflection.Missing.Value);<br />

var range = (Excel.Range) excel.Cells [1, 1];<br />

range.Font.FontStyle = "Bold";<br />

The fact that some COM methods return variants is often due<br />

to poor design more than to necessity.<br />

From C# 4.0, variant types are instead mapped to dynamic (if Embed Interop Types<br />

is enabled; more on this soon), allowing you to replace the last two lines with this:<br />

excel.Cells [1, 1].Font.FontStyle = "Bold";<br />

The disadvantage of working in this way is that you lose auto-completion, so you<br />

must know that a property called Font happens to exist. For this reason, it’s usually<br />

easier to dynamically assign the result to its known interop type:<br />

Excel.Range range = excel.Cells [1, 1];<br />

range.Font.FontStyle = "Bold";<br />

As you can see, this saves only five characters over the old-fashioned approach!<br />

The mapping of variant to dynamic is the default from Visual Studio 2010, and is a<br />

function of enabling Embed Interop Types on a reference.<br />

974 | Chapter 25: Native and COM Interoperability

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!