C# Params

There are cases when we don’t know the actual number of parameters in the function call. Well, in C# we can pass any number of parameters in the function call by using params prior to the formal parameters in function definition. It is a keyword which is used to specify a parameter which can take unknown number of arguments. Only params is allowed and no extra arguments can be passed.

C# Params Example:
using System;
public class ArrayExample
{
            void showValues(params int[] val)
            {
                        foreach(int i in val)
                        {
                                    Console.WriteLine(i);
                        }
            }
            public static void Main (string[] args)
            {
                        ArrayExample a1=new ArrayExample();
                        a1.showValues(1,2,3,4,5,6,7,8,9,10);
            }
}
Output
1
2
3
4
5
6
7
8
9
10                    
C# Params Example 2: passing unknown number of objects to the function
using System;
public class ArrayExample
{
            void showValues(params object[] val)
            {
                        foreach(object i in val)
                        {
                                    Console.WriteLine(i);
                        }
            }
            public static void Main (string[] args)
            {
                        ArrayExample a1=new ArrayExample();
                        a1.showValues("Ram",21,"B. Tech.");
            }
}
Output :
Ram
21
B. Tech.



ADVERTISEMENT
ADVERTISEMENT