C# MASTER

Variable Numbers of Method Arguements (params)

Back to Table of Contents

C# has the built in possibilty of using variable numbers of arguements (params) in a single method:

public int AddAll(params int[] myData){
	int d = 0;
	foreach (int i in myData){
	  d += i;
	}
	return d;
}
//calling this method:
int sum = AddAll(1, 2, 3);
//sum would equal 6.

Note how myData in the previous code is declared as an array of ints preceded by the keyword params. Only the last parameter in a method can be marked params, and it must be an array of a type. Though you can use object for the type to allow anything to be passed. Also, you can require at least a certain number of parameters by doing something like this example, where you require at least two parameters to make addAll make more sense:

public int AddAll(int A1, int A2, params int[] myData){
	int d = A1 + A2;
	foreach (int i in myData){
	  d += i;
	}
	return d;
}

With this method signature, you must now provide at least two parameters to the method call AddAll().

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*