To declare a method as a method that can accept a variable number of parameters, we can use the params keyword to declare an array, as follows:
public static Int32add (params int32[] values)
{
Int32 sum = 0;
for (Int32 x = 0; x < values. Length; X + +)
{
Sum + = values[x];
}
return sum;
}
Only the last parameter of the method can mark the params, which must identify a one-dimensional array, but not any type. It is legal to pass NULL or 0 number of array references to the last argument of the method, as the following code calls the Add method above, compiles normally, runs normally, and expects the same result as 0:
public static void Main ()
{
Console.WriteLine (Add ());
}
Here's a look at how to write a method that accepts any number of arbitrary types of arguments, that is, to change the Int32 of the above method to object[]:
public static void Main ()
{
Displaytypes (New Object (), New Random (), "string", 10);
}
public static void Displaytypes (params object[] objects)
{
foreach (Object o in objects)
{
Console.WriteLine (O.gettype ());
}
}
Output:
System.Object
System.Random
System.String
System.Int32
Note that a call to a method that accepts a variable number of parameters can cause a loss of performance because the array is allocated on the heap, the elements of the array are initialized, the memory of the array is recycled by the garbage collector, and to reduce this unnecessary performance penalty, we want to define several overloaded methods without the params keyword , such as the concat method of the System.String class, is as follows:
public static string Concat (object arg0);
public static string Concat (params object[] args);
public static string Concat (params string[] values);
public static string Concat (object arg0, Object arg1);
public static string Concat (String str0, string str1);
public static string Concat (object arg0, Object Arg1, Object arg2);
public static string Concat (String str0, String str1, String str2);
public static string Concat (object arg0, Object Arg1, Object arg2, Object Arg3);
public static string Concat (String str0, String str1, String str2, string str3);
Application of C # params