When working with methods that accept a variable number of the same type of parameters, the "params" keyword is essential for increasing flexibility and ease in C# programming.
C# parameters
This feature, which enables developers to send an arbitrary number of parameters or optional parameters of the same type in a method declaration, is especially helpful when the precise number of arguments is unknown in advance.
class Program
{
public static void AddItemsToShoppingBasket(params string[] items)
{
// ....
}
public static void AddItemsSumToShoppingBasket(params int[] sum)
{
// ....
}
}
Here, we do not know the count of items beforehand, and the method is written in such a way by specifying the params keyword that it accepts string items without specifying the count.
The params keyword is employed in this method signature declarations to denote that a parameter array can be passed to the method. This array can hold zero or more values of a specified type and can also be an optional parameter/hold optional arguments.
The default value for this parameter is an empty array of the type specified in the method signature. For example, when a method containing the argument 'params object[] objects' is called without any parameters, it creates an empty array of objects.
As shown below, "AddToShoppingBasket" can be invoked with a variable number of arguments of string parameters. The params keyword simplifies the syntax for the method call by allowing developers to pass the optional parameters directly without explicitly creating an array.
Now that we have introduced the params keyword in general let us dive deep into some considerations and best practices of the 'params' keyword.
The parameter type must be a one-dimensional array.
To use the params keyword specified in the method "AddItemsToShoppingBasket" defined above, we can pass a one-dimensional array instead of manually calling the method using parameters like below.
Can pass a comma-separated list of arguments for the type of the array elements.
While using a method with the params keyword, we can pass multiple values of arguments as comma-separated values.
The below code throws an error if we try to add items of type int into the shopping basket.
This occurs as the array argument is a string type and not an int type.
No additional parameters are permitted after the params parameter in a method signature declaration, and only one params argument is permitted in a method parameters declaration.
Params should be the last argument of the method signature. This means that all required parameters need to be specified before the params argument.
This is shown in the following code.
Only One params keyword.
There can only be one params parameter in a method signature.
You can pass no arguments.
If you send no arguments, the length of the params list is zero.
For any parameter with params, an argument is considered optional and can be called without passing parameters.
Here is a complete code example written in C# that shows how to pass different numbers of variables in a params method as a params argument and read these values back in the caller code.
In Visual Studio, select Create New Project to get the below window. Here, you can provide the Solution Name, Project Name, and paths. Once this information is entered, click next to create the console application ready to start coding.
Now, add the code below.
class Program
{
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] items)
{
for (int i = 0; i < items.Length; i++)
{
cart.Add(items[i]);
}
}
// caller code
static void Main(string[] args)
{
Console.WriteLine("Params Example");
Program program = new Program();
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
var items = itemsString.Split(",").ToArray();
program.AddItemsToShoppingBasket(items);
}
program.AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
foreach (var item in program.cart)
{
Console.WriteLine(item);
}
}
}
Output
The output of the above code looks like the following.
ASP.NET Core 9.0 Hosting Recommendation
At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.