N/Direct - The .NET Interoperability Resource Center 

FAQ

 

 

 

Most Valuable Professional

How do I handle optional COM method parameters in C#?
Written: 6/28/2002 Updated: 3/25/2003

Since C# lacks support for optional parameters, you have to specify all of them when calling the method.

To simulate leaving out an optional VARIANT parameter, you can pass in System.Type.Missing (or System.Reflection.Missing.Value, which is the same thing). The result, as seen from the callee, is a VARIANT of type VT_ERROR with error code DISP_E_PARAMNOTFOUND (0x80020004).

C#
object m = Type.Missing;
ComObj.SomeMethod( param1, param2, ref m, ref m );
    

For types other than VARIANT, there is no magic value to indicate that the parameter was not specified. Instead, a default value has to be provided in the type library, and the type library importer preserves this default value in the interop assembly metadata. C# users will have to look up this default value, either from the type library with OleView, or from the interop assembly with ILDASM, and then pass in this value explicitly.

Here's an example of how a methods with default parameter values can look like in IDL

        HRESULT OptionalParams(
          [in, optional, defaultvalue("xyzzy")] BSTR s, 
          [in, optional, defaultvalue(123)] long i, 
          [in, optional, defaultvalue(456,78)] double d, 
          [in, optional, defaultvalue(-1)] VARIANT_BOOL b);
    

And this is how the same method might look in IL assembler.

      .method public virtual instance void OptionalParams(
        [in][opt] string marshal( bstr) s,
        [in][opt] int32 i,
        [in][opt] float64 d,
        [in][opt] bool f) runtime managed internalcall
      {
        .param [1] = "xyzzy"
        .param [2] = int32(0x0000007B)
        .param [3] = float64(456.78)
        .param [4] = bool(true)
      }
    

See also
HOW TO: Pass Optional Method Arguments from C# (305814)