Java vs. C#

Parameter Array


Java
 
Java 5 adds such feature. Below Java 5, you may work around like followings.

public class Test
{
    public static void main (String[] args) {
        System.out.println(add (new int[] {1,2,3,4}));
    }

    public static int add (int[] array) {
       int sum = 0;
       for(int i = 0; i < array.length; i++)
           sum += array[i];
       return sum;
    }
}

prints: 10

class Test { static void F(int[] args) { System.out.println("# of arguments: " + args.length); for (int i = 0; i < args.length; i++) System.out.println("args[" + i + "] = " + args[i]); } public static void main(String[] args) { F(); //error F(1); //error F(1, 2); //error F(1, 2, 3);//error F(new int[] {1, 2, 3, 4}); } }
class Test { static void F(Object[] args) { for(int i = 0; i < args.length; i++) { Object o = args[i]; System.out.println(o.getClass().getName()); } } public static void main(String[] args) { Object[] a = {new Integer(1), "Hello", new Double(123.456)}; Object o = a; F(a); //F((Object)a);//error //F(o);//error F((Object[])o); } } prints: java.lang.Integer java.lang.String java.lang.Double java.lang.Integer java.lang.String java.lang.Double
In Java 5: public void aMethod(String... args) { for(String s : args) { System.out.println(s); } } The aMethod can be called in the following ways: aMethod("here","we","go"); //3 argument list aMethod("to","be","or","not","to","be"); //6 argument list Note that the compiler will translate the aMethod automatically as: aMethod(new String[] {"here","we","go"}); aMethod(new String[] {"to","be","or","not","to","be"});

C#
 
The params modifier may be added to the last parameter 
of a method so that the method accepts any number of 
parameters of a particular type
public class Test
{
    public static void Main () {
        Console.WriteLine (add (1, 2, 3, 4).ToString());
    }

    public static int add (params int[] array) {
       int sum = 0;
       foreach (int i in array)
           sum += i;
       return sum;
    }
}
prints: 10

class Test { static void F(params int[] args) { Console.WriteLine("# of arguments: {0}", args.Length); for (int i = 0; i < args.Length; i++) Console.WriteLine("\targs[{0}] = {1}", i, args[i]); } static void Main() { F(); F(1); F(1, 2); F(1, 2, 3); F(new int[] {1, 2, 3, 4}); } }
using System; class Test { static void F(params object[] args) { foreach (object o in a) { Console.Write(o.GetType().FullName); Console.Write(" "); } Console.WriteLine(); } static void Main() { object[] a = {1, "Hello", 123.456}; object o = a; F(a); F((object)a); F(o); F((object[])o); } } prints: System.Int32 System.String System.Double System.Object[] System.Object[] System.Int32 System.String System.Double