We received a support question recently concerning methods in .NET with optional parameters, and how to call them from Java. This is something that I think would be of interest to a number of our users.
If a method has optional parameters, they can be left out of the arguments when the method is called. For example, in the method
Microsoft.VisualBasic.Collection.Add(Object Item, string key, Object Before, Object After),
the last three parameters are optional and can be omitted. Optional parameters are most common in Visual Basic, although they also appear in C# starting with C# 2010. They can be used in methods, indexers, constructors, and delegates.
The original support question asked how one would call Collection.Add() when one wanted to leave out one or more of the optional parameters. When Collection.Add() is proxied, only the four-parameter version is proxied. Making the call with only, say, two parameters leads to a compilation error.
In order to know what to do when calling methods with optional parameters from Java, it makes sense to first understand what is really happening when such methods are called. If a method is called without an argument for an optional parameter, a default value is passed in place of the missing argument. The default value is chosen according to the following rules:
- If the parameter is of type Object, the default value is Type.Missing
- If the parameter is any other reference type, the default value is null
- If the parameter is a value type, the default of the particular value type is passed
In the case of Collection.Add(), the full four-parameter version of the method is always called (it’s the only one that actually exists), and the compiler automatically and transparently inserts default values for the missing arguments.
Knowing that, it’s easy to see what to do when calling such methods from Java. Call the full-parameter version of the method (which is what has been proxied), and use the default values for any parameters whose values you ordinarily wouldn’t pass. In the case of Object parameters, pass Type.Get_Missing() – System.Type is always proxied, and Missing is a property, so it’s accessed using its getter method. Note that since the proxied Type class is in the System.* namespace, you’ll need to do something special to avoid compilation errors – see the knowledge base article here for more information.
Do you have a question about how to do something using JNBridgePro? Contact us at firstname.lastname@example.org.