Call .NET Methods with Optional Arguments

Setting Up the Examples

To use the examples in this topic, build the NetDocOptional assembly. This C# example, NetDocOptional.cs in the matlabroot/extern/examples/NET/NetSample folder, defines the methods used in these examples. To see the code, open the fileopen the file in MATLAB® Editor. To build the NetDocOptional assembly, see Build a .NET Application for MATLAB Examples. The examples assume you put the assembly in your c:\work folder. You can modify the examples to change the path to the assembly.

Skip Optional Arguments

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

 Greeting Function Signature

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

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

Display the default values.

Greeting(obj,0)
ans = 
hello world

Use the default value for str1.

def = System.Reflection.Missing.Value;
Greeting(obj,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(obj,0,'My')
ans = 
My world

Call Overloaded Methods

This example shows how to use optional arguments with an overloaded method, calc.

 calc Function Signatures

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

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

Call calc with explicit arguments.

calc(obj,3,4)
ans =
     7

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

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

'NetDocOptional.MyClass.calc(NetDocOptional.MyClass this, 
optional<int32 scalar> x, optional<single scalar> y)' and
'NetDocOptional.MyClass.calc(NetDocOptional.MyClass 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(obj,def,def)
calc(obj,3,def)
calc(obj,def,4)
ans =
    44
ans =
    14
ans =
    37
Was this topic helpful?