Java vs. C#

Out Parameters


Java
 
Java doesn't have out parameters.
You can achieve C#'s functionality by wrapping a primitive 
to a class, or using an array to hold multiple returned values, 
and then call back that value via pass by reference.

class Test {
    static void divide(int a, int b, int result, int remainder) {
        result = a / b;
        remainder = a % b;
        System.out.println(a +"/"+ b + " = "+ result + 
               " r " + remainder);
    }
    public static void main(String[] args) {
        for (int i = 1; i < 10; i++)
            for (int j = 1; j < 10; j++) {
                int ans = 0, r = 0;
                divide(i, j, ans, r);
            }
    }
}

class Test { static void SplitPath(String path, String dir, String name) { int i = path.length(); while (i > 0) { char ch = path.charAt(i-1); if (ch == '\\' || ch == '/' || ch == ':') break; i--; } dir = path.substring(0, i); name = path.substring(i); System.out.println(dir); System.out.println(name); } public static void main(String[] args) { String dir="", name =""; SplitPath("c:\\Windows\\System\\hello.txt", dir, name); } } prints: c:\Windows\System\ hello.txt

Thanks for Peter's suggestion. He suggests to use an array as one of possible solutions in Java to replace out parameter feature in C#.

C#
 
C# provides the out keyword, which indicates that you may pass in 
uninitialized variables and they will be passed by reference. 
Note the calling method should mark out keyword either.


class Test {
    static void Divide(int a, int b, out int result, out int remainder) {
        result = a / b;
        remainder = a % b;
    }
    static void Main() {
        for (int i = 1; i < 10; i++)
            for (int j = 1; j < 10; j++) {
                int ans, r;
                Divide(i, j, out ans, out r);
                Console.WriteLine("{0} / {1} = {2}r{3}", i, j, ans, r);
            }
    }
}


using System; class Test { static void SplitPath(string path, out string dir, out string name) { int i = path.Length; while (i > 0) { char ch = path[i - 1]; if (ch == '\\' || ch == '/' || ch == ':') break; i--; } dir = path.Substring(0, i); name = path.Substring(i); } static void Main() { string dir, name;//like a place holder SplitPath("c:\\Windows\\System\\hello.txt", out dir, out name); Console.WriteLine(dir);//call back Console.WriteLine(name); } } prints: c:\Windows\System\ hello.txt