Information Technology Reference
In-Depth Information
uses. Named parameters work with optional parameters to limit the nois-
iness around many APIs, especially COM APIs for Microsoft Office. This
small snippet of code creates a Word document and inserts a small amount
of text, using the classic COM methods:
var
wasted =
Type
.Missing;
var
wordApp =
new
Microsoft.Office.Interop.Word.
Application
();
wordApp.Visible =
true
;
Documents
docs = wordApp.Documents;
Document
doc = docs.Add(
ref
wasted,
ref
wasted,
ref
wasted,
ref
wasted);
Range
range = doc.Range(
0
,
0
);
range.InsertAfter(
"Testing, testing, testing. . ."
);
This small, and arguably useless, snippet uses the Type.Missing object four
times. Any Office Interop application will use a much larger number of
Ty p e . M i s s i n g o b j e c t s i n t h e a p p l i c a t i o n . T h o s e i n s t a n ce s c l u t te r u p yo u r
application and hide the actual logic of the software you're building.
That extra noise was the primary driver behind adding optional and
named parameters in the C# language. Optional parameters means that
these Office APIs can create default values for all those locations where
Ty p e . M i s s i n g wo u l d b e u s e d . T h a t s i m p l i fi e s e ve n t h i s s m a l l s n i p p e t :
var
wordApp =
new
Microsoft.Office.Interop.Word.
Application
();
wordApp.Visible =
true
;
Documents
docs = wordApp.Documents;
Document
doc = docs.Add();
Range
range = doc.Range(
0
,
0
);
range.InsertAfter(
"Testing, testing, testing. . ."
);
Even this small change increases the readability of this snippet. Of course,
you may not always want to use all the defaults. And yet, you still don't
want to add all the Type.Missing parameters in the middle. Suppose you