In the C# programming language, the Params keyword is used to define a parameter that accepts a variable number of arguments. It is an important keyword in C#. It enables calling a method with zero or more arguments without explicitly creating an array and allows a method to accept a variable number of arguments of specific data. It must be used in a Single-dimensional array.
It has the following syntax:
return_type MethodName(params data_type[] parameterName)
{
// Method body
}
Let us take an example to illustrate the Params keyword in C#.
Output:
The integer values are 1 2 3 4 5 The String values are Hello World C# Params
Explanation:
In this example, we demonstrate how to define the Params keyword in C#. First, we create two methods: one takes any number of integers, and the other takes any number of strings. In the main() method, we create an instance of the Program class and call the Show() method. Finally, we use the Console.WriteLine() function to print the output.
Let us take an example to illustrate how to use the params keyword for a variable number of arguments in C#.
Output:
Krishna John 11 20.5 Peter X
Explanation:
In this example, we demonstrate how to use params for a variable number of arguments. First, we define the method named DisplayItems() that accepts a variable number of arguments of any type. After that, we use a for loop to iterate over each item in the array and print it by using the Console.WriteLine() function. In the main() method, we create an object of the program class and call the DisplayItem() method.
Let us take an example to illustrate how we can add the element of an array that is passed to the method in C#.
Output:
The total sum of the given numbers is 150
Explanation:
In this example, we create a method named Sum that takes any number of integer arguments. After that, we use the foreach loop to calculate the sum of the given numbers. In the main method, we call the method Sum() with five integer values (10, 20, 30, 40, 50). Finally, it displays the output using the Console.WriteLine() function.
In the C# programming language, a params keyword is mainly utilized to define a parameter that accepts a variable number of arguments. Instead of creating multiple overloaded methods for different parameters, we can define a single method that automatically handles any number of inputs. It helps to improve the code readability and maintainability. It can simply pass an array as an argument.
There are several rules that help to create the params in C#. Some of them are as follows:
We request you to subscribe our newsletter for upcoming updates.