This is a mirror of official site: http://jasper-net.blogspot.com/

C# 4.0: COM Interop Improvements

| Sunday, November 14, 2010
Dynamic resolution as well as named and optional arguments greatly improve the experience of interoperating with COM APIs such as Office Automation Primary Interop Assemblies (PIAs). But, in order to alleviate even more COM Interop development, a few COM-specific features were also added to C# 4.0.

Dynamic resolution as well as named and optional arguments greatly improve the experience of interoperating with COM APIs such as Office Automation Primary Interop Assemblies (PIAs). But, in order to alleviate even more COM Interop development, a few COM-specific features were also added to C# 4.0.

Omitting ref

Because of a different programming model, many COM APIs contain a lot of reference parameters. These parameters are typically not meant to mutate a passed-in argument, but are simply another way of passing value parameters.

Specifically for COM methods, the compiler allows to declare the method call passing the arguments by value and will automatically generate the necessary temporary variables to hold the values in order to pass them by reference and will discard their values after the call returns. From the point of view of the programmer, the arguments are being passed by value.

This method call:

object fileName = "Test.docx";
object missing = Missing.Value;

document.SaveAs(ref fileName,
   ref missing, ref missing, ref missing,
   ref missing, ref missing, ref missing,
   ref missing, ref missing, ref missing,
   ref missing, ref missing, ref missing,
   ref missing, ref missing, ref missing);

can now be written like this:

document.SaveAs("Test.docx",
   Missing.Value, Missing.Value, Missing.Value,
   Missing.Value, Missing.Value, Missing.Value,
   Missing.Value, Missing.Value, Missing.Value,
   Missing.Value, Missing.Value, Missing.Value,
   Missing.Value, Missing.Value, Missing.Value);

And because all parameters that are receiving the Missing.Value value have that value as its default value, the declaration of the method call can even be reduced to this:

document.SaveAs("Test.docx");

Read more: Codeproject

Posted via email from .NET Info

0 comments: