# Programming Office in C#

5/28/2004 4:04:08 PM

## Programming Office in C#

Cyrus Blather was commenting on development with the Microsoft Office object model. When creating Office applications, VB is definitely preferred over C# because OLE Automation was originally designed as a way for VB programmers to programmatically drive other applications.

Unfortunately, VB supports a number of concepts that are awkward to express in other languages such as by-ref parameters on by default (in VB 6.0), missing parameters and named parameters (in addition to positional parameters).

For example, Cyrus Blather contrasted VB with C#.

VB:

C#:
Document d = Word.Documents.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);


Actually, Cyrus had it wrong. His C# version is still too simplified and won't compile. He needs to modify it:

missing = Type.Missing;
Document d = Word.Documents.Open(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, true, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing)


First, OLE Automation had no notions of multiple methods with the same name, so one method had to take in many arguments. Since C# doesn't support missing arguments directly and named parameters, it must include all 30 arguments. Luckily, the Excel object model, unlike Word's, does not use by-ref parameters, so the ref syntax can be dropped in Excel.

Second, Word and Excel commands tend to have many arguments--as many as 30 or 31. That's only because that is the limit of the number of controls in a dialog or tab panel. These long commands almost always correspond to a dialog window that exists in Office. You will generally find a one-to-one correspondence between a dialog control and an argument. These commands essentially simulate the user interaction with the dialog without actually displaying the dialog, with the missing arguments automatically filled in with the default dialog value.

While definitely not object-oriented in the inheritance sense, this approach has many benefits in getting the product out the door, such as reducing the testing cost and simplifying development of features like recording, which have to map a user's actions in a dialog to VBA code.

Anyway, C# is just not a good language to program Office applications, not without a good library to simplify the syntax. Score one for VB.NET.