Main Content

Call .NET Methods with Optional Arguments

Skip Optional Arguments

This example shows how to use default values in optional arguments using the Greeting method.

 Greeting Function Signature

Build the C# example, NetDocOptional.cs in the matlabroot/extern/examples/NET/NetSample folder. For information about building the assembly, see Build a .NET Application for MATLAB Examples.

Load the NetDocOptional assembly, if it is not already loaded.

dllPath = fullfile('c:','work','NetDocOptional.dll');
asm = NET.addAssembly(dllPath);
cls = NetDocOptional.MyClass;

The example assumes that you put the assembly in your c:\work folder. You can modify the fullfile function to change the path to the assembly.

Display the default values.

Greeting(cls,0)
ans = 
hello world

Use the default value for str1.

def = System.Reflection.Missing.Value;
Greeting(cls,0,def,'Mr. Jones')
ans = 
hello Mr. Jones

Use the default value for str2. You can omit the argument at the end of a parameter list.

Greeting(cls,0,'My')
ans = 
My world

Call Overloaded Methods

This example shows how to use optional arguments with an overloaded method, calc. To run the example, you must create and build your own assembly Doc defining the calc method in Class with the following function signatures.

 calc Function Signatures

Load your assembly and create cls.

cls = Doc.Class;

Call calc with explicit arguments.

calc(cls,3,4)
ans =
     7

If you try to use the default values by omitting the parameters, MATLAB® cannot determine which signature to use.

calc(cls)
Cannot choose between the following .NET method signatures due to 
unspecified optional arguments in the call to 'calc':

'Doc.Class.calc(Doc.Class this, 
optional<int32 scalar> x, optional<single scalar> y)' and
'Doc.Class.calc(Doc.Class this, 
optional<int32 scalar> x, optional<double scalar> y)'

You can resolve this ambiguity by specifying enough additional 
optional arguments so that there is only one possible matching 
.NET method.

To use the default values, you must provide both arguments.

def = System.Reflection.Missing.Value;
calc(cls,def,def)
calc(cls,3,def)
calc(cls,def,4)
ans =
    44
ans =
    14
ans =
    37