The params keyword in C#
Params keyword is useful to specify a method
parameter that takes a variable number of arguments in C#. The params keyword is useful when we are not sure
about the number of arguments to send as a parameter.
During method declaration only one params keyword is allowed and no additional parameters are permitted after the params keyword in a method declaration in C#.
We can send arguments of the specified type as a comma-separated list or an array to the declared parameter. In case, if we are not sending any arguments to the defined parameter, then the length of params list will become a zero.
Example in C#
The following is the example of using params keyword in C# to specify method parameter accept the multiple numbers of arguments.
namespace CsharpnaijaTutorial
{
class Program
{
static void Main(string[] args)
{
ParamsMethod(1, 2, 3, 4, 5, 6);
}
public static void ParamsMethod(params int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + (i < arr.Length - 1 ? ", " : ""));
}
Console.WriteLine();
Console.WriteLine("\nPress Enter Key to
Exit..");
Console.ReadLine();
}
}
}
From above example, we
are sending a comma separated list of multiple arguments of the specified type
(integer) to the declared parameter in ParamsMethod function.
object
type parameter in the method
declaration.
Params Keyword with Object Type
The following is the example of using object
type parameter in a method
declaration to accept the list of multiple types of arguments.
using System;
namespace CsharpnaijaTutorial
{
class Program
{
static void Main(string[] args)
{
ParamsMethod(1, 2, "Musa", "Sule", "Gadabs", 10.26);
}
public static void ParamsMethod(params object[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + (i < arr.Length - 1 ? ", " : ""));
}
Console.WriteLine();
Console.WriteLine("\nPress Enter Key to
Exit..");
Console.ReadLine();
}
}
}
The above example, we
used object
type parameter in method declaration and accepting
different data type of arguments as a list.
References
2. Tutlane
3. JavatPoint
Comments
Post a Comment