Optional Arguments

Added in .NET 4.0
Also referred to as Optional Parameters


Default Values

Optional parameters allow you to omit the argument when you want to use the parameters default value.
Optional parameters cannot be marked as "ref" or "out".
In earlier version you had to submit System.Type.Missing
you can make parameters optional by assigning them default values
Optional parameters must always follow mandatory ones
When calling methods with optional parameters you can leave out one or more of the optional parameters
When an optional parameter is not provided the default value is used
This feature was introduced to support legacy APIs (especially Office) and should be used sparingly in new code


A large number of the Microsoft Office methods allow 20 or more optional parameters.
When parameters are not submitted their default values are used instead.
Optional parameters in VBA appear at the end of a declaration and it is the same in C#.

public bool Folder_Exists(string sFolderPath, 
                          bool bInformUser = false)
{
}

static int Sum(int var1 = 1, int var2 = 2) 
{
   return var1 + var2;
}
Sum(); // 1 + 2 = 3
Sum(4); // 4 + 2 = 6
Sum(4,5); // 4 + 5 = 9

Overloading

Default parameters were only introduced in .NET 4.0
Prior to that you had to use a different approach if you wanted to achieve the same thing.
This alternative was to use method overloading

string MyMethod (int start) 
string MyMethod (int start, int finish)

.NET 3.5 and earlier

C# does not support optional parameters because it supports method overloading.


System.Type.Missing
C# does not support optional parameters so you must pass "System.Type.Missing" instead
This is automatically declared for you in the following files:
ThisAddIn.Designer.cs
Sheet1.Designer.cs
Sheet2.Designer.cs
Sheet3.Designer.cs
ThisDocument.Designer.cs

[private global::System.Object missing = global::System.Type.Missing] 

Excel
Optional parameters in VBA appear at the end of a declaration.
When parameters are ignored they will accept their default values.
Therfore every parameter defined by a method must be passed to the caller.


Excel.Workbook objWorkbook = Application.Workbooks.Open(@"C;\temp\myfile.xlsx", 
System.Reflection.Missing.Value (* 14)

You can only pass the System.Type.Missing value for parameters that accept reference types
For value type paramaters you must pass in the actual default value.
If an optional paramater is an enumeration rather than an object, then you must specify a corresponding enumeration value.

Excel.Range objRange; 
objRange.Sort(objRange,
              Excel.xlSortOrder.xlAscending,
              System.Reflection.Missing.Value,
              System.Reflection.Missing.Value,
              Excel.xlSortOrder.xlAscending
              System.Reflection.Missing.Value,
              Excel.xlSortOrder.xlAscending
              System.Reflection.Missing.Value,
              System.Reflection.Missing.Value,
              Excel.xlSortOrientation.xlSortColumns
              Excel.xlSortOrientation.xlSortColumns
              Excel.xlSortOrientation.xlSortColumns);

Another example where there are lots of optional parameters is Application.WorksheetFunction. In fact these functions require 29 arguments.
Because Optional parameters are not strongly typed any mismatches between the type passed in and the type expected will not be found until runtime.


Wrapper for Populating Optional Paramaters
In some cases though if a method is called a lot it might be useful to create a wrapper method to automatically populate the optional parameters.
First declare the delegate

private delegate double WorksheetFunction_Delegate( 
   object objValue1,
   object objValue2,
   ..
   object objValue30);

The create the wrapper function

private double WorksheetFunction_Call( 
   WorksheetFunction_Delegate delFunction,
   object objValue,
   params object[] aParamValues)
{
   object[] arguments = new object[29];
   aParamValues.CopyTo(arguments, 0);
   for (int icount = aParamValues.Length; icount < arguments.Length; icount++)
   {
      arguments[icount] = System.Reflection.Missing.Value;
   }

   return delFunction(
      objValue,
      arguments[0],
      arguments[1],

      arguments[28],
}

Once the delegate and wrapper function have been created calling a built-in worksheet function is relatively straightforward.
This calls a worksheet function that accepts 1 argument.

WorksheetFunction_Delegate fn_MIN = new WorksheetFunction_Delegate(Application.WorksheetFunction.Min); 
System.Windows.Forms.MessageBox.Show(WorksheetFunction_Call(
   fn_MIN, objRange, new object[] {System.Reflection.Missing.Value }).ToString();

This calls a worksheet function that accepts 3 arguments.

System.Windows.Forms.MessageBox.Show(WorksheetFunction_Call( 
   fn_333, objRange1, new object[] {objRange2, objRange3 }).ToString();

Word
Optional parameters in Word are treated the same as optional parameters in Excel.
It is slightly more complicated in Word though because you have to pass most of the parameters by reference.
For more information on passing them by reference, refer to Classes > Arguments > ref
You must declare a variable, set it to System.Type.Missing and then pass that variable by reference
If the missing variable has been predefined you can just use that

object missing = System.Type.Missing; 

Normally when you pass variables by reference its value can be changed
Passing System.Type.Missing however as a paramater actually sends a special COM value indicating the value is actually missing.
This special case only applies when you are using COM Interop to an unmanaged object model

string sfilename = "C:\temp\myfile.docx" 
Application.Documents.Open(ref sfilename,
    ref System.Reflection.Missing.Value (*15)

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext