C# FAQ: What are the differences between CSharp and Java variable length parameter lists

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

What are the differences between the C# and Java variable length parameter lists?

In both the C and C++ languages, a method declaration can be specified that takes a variable number of arguments. And, both the C# and Java languages support a parameter syntax that specifies that a variable number of arguments may be passed to a method.

In C#, the syntax for specifying a variable number of arguments uses the params keyword as a qualifier to the last method argument—which should be an array. The following is an example:

using System;
 
class CSharpParams
{
   public static void PrintIntegers (params int[] integers)
   {
      foreach (int number in integers)
      {
         Console.WriteLine (number); 
      }
   }
 
   public static void Main (string[] args)
   {
      PrintIntegers (1, 2, 3);  // call with any number of arguments
   }
}

In the Java syntax, the string "..." is appended to the type name of the last method argument as in the following example:

class JavaParams
{
   public static void PrintIntegers (Integer... integers)
   {
      for (int number : integers)
      {
        System.out.println (number); 
      }
    }
 
   public static void main(String[] args)
   {
      PrintIntegers (1, 2, 3);  // call with any number of arguments
   }
}

See also





Personal tools