Codeporting C#2java Engine converts C# optional arguments to java in such a way that they remain usable in generated java code which helps developers in a lot of ways. It can be specified from the definition of a constructor, method, indexer or delegate that its parameters are required or they are optional. Arguments must be provided for required parameters but they can be omitted for the optional parameters. If no Argument is sent for the optional parameter its default value is used. CodePorting C#2Java engine automatically handle this overload intelligently.
Following example shows how CodePorting automatically converts C# optional arguments to java:
C# Code:
using System;
namespace CsPorter.Tests.Convert.DefaultParameters
{
class DefParamerters
{
static void Main(string[] args)
{
ExampleClass anExample = new ExampleClass("Test");
anExample.ExampleMethod(1, "One", 1);
anExample.ExampleMethod(2, "Two");
anExample.ExampleMethod(3);
ExampleClass anotherExample = new ExampleClass("Provided name");
anotherExample.ExampleMethod(1, "One", 1);
anotherExample.ExampleMethod(2, "Two");
anotherExample.ExampleMethod(3);
}
}
class ExampleClass
{
private string _name;
public ExampleClass(string name = "Default name")
{
_name = name;
}
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
Console.WriteLine(optionalstr);
}
}
}
Java Code Generated by CodePorting:
package CsPorter.Tests.Convert.DefaultParameters;
// ********* THIS FILE IS AUTO PORTED FORM C# USING CODEPORTING.COM *********
class Test1 {
static void main(String[] args) {
ExampleClass anExample = new ExampleClass("Test");
anExample.exampleMethod(1, "One", 1);
anExample.exampleMethod(2, "Two");
anExample.exampleMethod(3);
ExampleClass anotherExample = new ExampleClass("Provided name");
anotherExample.exampleMethod(1, "One", 1);
anotherExample.exampleMethod(2, "Two");
anotherExample.exampleMethod(3);
}
}
class ExampleClass {
private String _name;
public ExampleClass(String name) {
_name = name;
}
// Auto generated code to handle default paramters
public void exampleMethod(int required) {
String optionalstr = "default string";
int optionalint = 10;
exampleMethod(required, optionalstr);
}
// Auto generated code to handle default paramters
public void exampleMethod(int required, String optionalstr) {
int optionalint = 10;
exampleMethod(required, optionalstr, optionalint);
}
public void exampleMethod(int required, String optionalstr, int optionalint) {
System.out.printf(optionalstr);
}
}
It is clear from the above example that CodePorting generates three overloads of exampleMethod which were required to handle optional arguments in Java.