Thursday, February 10, 2011

Variable Length Parameter Lists

In C and C++ it is possible to specify that a function takes a variable number of arguments. This functionality is used extensively in the printf and scanf family of functions. Both C# and Java allow one to define a parameter that indicates that a variable number of arguments are accepted by a method. In C#, the mechanism for specifying that a method accepts a variable number of arguments is by using the params keyword as a qualifier to the last argument to the method which should be an array. In Java, the same effect is achieved by appending the string "..." to the typename of the last argument to the method.
C# Code
using System;

class ParamsTest{

public static void PrintInts(string title, params int[] args){

Console.WriteLine(title + ":");

foreach(int num in args)
Console.WriteLine(num);

}


public static void Main(string[] args){

PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
}

}
Java Code
class Test{

public static void PrintInts(String title, Integer... args){

System.out.println(title + ":");

for(int num : args)
System.out.println(num);

}

public static void main(String[] args){

PrintInts("First Ten Numbers in Fibonacci Sequence", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34);
}

}

No comments:

Post a Comment