Sometimes a situation may arise where you do not know how many parameters you want to pass to a method or you may want the method to accept n number of parameters at runtime. In such times params type array can solve the problem. param
is a keyword in C# that creates an array at runtime that receives and holds as many numbers of parameters as you want.
The length of params will be zero if no arguments will be passed. Although only one params keyword is allowed and no other parameters are allowed after the method declaration.
Let us see it in a program.
C# Program to demonstrate the params Array
Let us create two classes, one class will contain the method and another class where the main
class will be present. The method will be accessed by creating an instance of the class in the main function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using System; namespace Arrays { class ParamsArray { public int SumElements(params int[] arr) { int sum = 0; foreach(int i in arr) { sum += i; } return sum; } } //main function class class MainClass { static void Main(string[] args) { //creating an object of ParamsArray class ParamsArray paramArray = new ParamsArray(); int result = paramArray.SumElements(10, 20, 30, 40, 50); Console.WriteLine("The sum of the result: {0}", result); } } } |
Output:
1 2 | //Output: The sum of the result: 150 |
Example: C# Program to pass different data-types and print them
Let us see another example where we pass different data-type inputs and print them all with param. We will use object type params that allow us to enter as many numbers of inputs as we want of different data types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | using System; namespace Arrays { class ParamProgram { // Print function (user-defined) public void DisplayFunc(params object[] elements) { Console.WriteLine("Displaying all the different types elements:"); for (int i = 0; i < elements.Length; i++) { Console.WriteLine(elements[i]); } } // Main function static void Main(string[] args) { // Creating Object of class ParamProgram ParamProgram program = new ParamProgram(); // Passing arguments of different types program.DisplayFunc("John Snow", 456, 30.25, "simple2code.com", 'Z', "Coder"); } } } |
Output:
1 2 | //Output: The sum of the result: 150 |