In this chapter you will learn:
- What is param array in C#?
- What is the advantage of using param array?
- How to use param array in C# programming?
Sometimes, you are not assured about a number of parameters or you want to create a method that can accept n number of parameters at runtime. This situation can be handled with params type array in C#. The params keyword creates an array at runtime that receives and holds n number of parameters.
static int add(params int[] allnumber)
In the preceding line, the allnumber variable can holds n number of parameters at runtime because it is declared with params keyword.
Programming Example of Params Array in C#
In this example, we are creating a function add() that will receive any number of integer parameters at runtime and returns the sum of all those numbers. We will use params array to achieve this goal in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace params_array { class Program { static int add(params int[] allnumber) { int sum = 0; foreach (int n in allnumber) { sum = sum + n; } return sum; } static void Main(string[] args) { int sum; // passing three parameters sum = Program.add(1, 2, 3); Console.WriteLine("Sum of 1,2,3 is:\t{0}", sum); // passing five parameters sum = Program.add(3, 5, 2, 6, 2); Console.WriteLine("Sum of 3,5,2,6,2 is:\t{0}", sum); Console.ReadLine(); } } }
Output
Sum of 1,2,3 is: 6
Sum of 3,5,2,6,2 is: 18
__
Summary
In this chapter you learned about param array in C#. You also learned how to use param array in C# programming. In next chapter you will learn how to pass array as parameter.