In C#, params is a keyword which is used to specify a parameter that takes variable number of arguments. It is useful when we don't know the number of arguments prior. Only one params keyword is allowed and no additional parameter is permitted after params keyword in a function declaration.
C# Params Example 1
- using System;
- namespace AccessSpecifiers
- {
- class Program
- {
-
- public void Show(params int[] val)
- {
- for (int i=0; i<val.Length; i++)
- {
- Console.WriteLine(val[i]);
- }
- }
-
- static void Main(string[] args)
- {
- Program program = new Program();
- program.Show(2,4,6,8,10,12,14);
- }
- }
- }
Output:
C# Params Example 2
In this example, we are using object type params that allow entering any number of inputs of any type.
- using System;
- namespace AccessSpecifiers
- {
- class Program
- {
-
- public void Show(params object[] items)
- {
- for (int i = 0; i < items.Length; i++)
- {
- Console.WriteLine(items[i]);
- }
- }
-
- static void Main(string[] args)
- {
- Program program = new Program();
- program.Show("Santosh Kumar Singh","Tanu",101, 20.50,"Biveka", 'A');
- }
- }
- }
Output:
Santosh Kumar Singh
Tanu
101
20.5
Biveka
A
No comments:
Post a Comment