‘missing’ in action with C#


When programming in C#–if you want to omit an optional parameter for a method in the Excel object model, you have to pass System.Type.Missing to the parameter:


myExcelApp.MethodWithOptionalParameter(System.Type.Missing);


When you want to omit an optional parameter in Word, you have to declare a variable of type object, set it to System.Type.Missing, and pass it by reference to the parameter:


object m = System.Type.Missing;
myWordApp.MethodWithOptionalParameter(ref m);


VSTO provides a useful aid that can be used in both of these situations.  When you write code in a VSTO project item class like Sheet1, ThisWorkbook, or ThisDocument, VSTO pre-declares a member variable in the class called missing that it sets to System.Type.Missing.  So when you are writing code in a VSTO class you can use the missing variable already declared for you and write code like this:


private void ThisDocument_Startup(object sender, System.EventArgs e)
{
  this.CheckSpelling(ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing);
}


This may not seem like much, but it actually simplifies your C# code and makes it look quite a bit cleaner when doing C# programming against Office.


Of course, if you are a VB.NET programmer your language already gives you a beautiful solution–you can omit optional parameters altogether.  Go find a C# developer and rub it in.


Private Sub ThisDocument_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
  Me.CheckSpelling()
End Sub


Comments (1)