Information Technology Reference
In-Depth Information
wanted to create a new Web page instead of new Word document. That's
the last parameter of four in the Add() method. Using named parameters,
you can specify just that last parameter:
var wordApp = new
Microsoft.Office.Interop.Word. Application ();
wordApp.Visible = true ;
Documents docs = wordApp.Documents;
object docType = WdNewDocumentType .wdNewWebPage;
Document doc = docs.Add(DocumentType : ref docType);
Range range = doc.Range( 0 , 0 );
range.InsertAfter( "Testing, testing, testing. . ." );
Named parameters mean that in any API with default parameters, you
only need to specify those parameters you intend to use. It's simpler than
multiple overloads. In fact, with four different parameters, you would need
to create 15 different overloads of the Add() method to achieve the same
level of flexibility that named and optional parameters provide. Remem-
ber that some of the Office APIs have as many as 16 parameters, and
optional and named parameters are a big help.
I left the ref decorator in the parameter list, but another change in C# 4.0
makes that optional in COM scenarios. That's because COM, in general,
passes objects by reference, so almost all parameters are passed by refer-
ence, even if they aren't modified by the called method. In fact, the Range()
call passes the values (0,0) by reference. I did not include the ref modifier
there, because that would be clearly misleading. In fact, in most produc-
tion code, I would not include the ref modifier on the call to Add() either.
I did above so that you could see the actual API signature.
Of course, just because the justification for named and optional parame-
ters was COM and the Office APIs, that doesn't mean you should limit
their use to Office interop applications. In fact, you can't. Developers call-
ing your API can decorate calling locations using named parameters
whether you want them to or not.
This method:
private void SetName( string lastName, string firstName)
{
 
Search WWH ::




Custom Search