use of params keyword in c#



# params keyword :- In C#, params keyword 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.
 
   class Program
    {
        static void Main(string[] args)
        {
            Program program = new Program();
            program.Show(2, 4, 6, 8, 10, 12, 14);     // passing arguments of variable length 
        }
         
        public void Show(params int[] val)             // params  parameter 
        {
            for (int i = 0; i < val.Length; i++)
            {
                Console.WriteLine(val[i]);
            }
        }       
    } 

Note:- 
·No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration. 

·
The parameter type must be a single-dimensional array .If the declared type of the params parameter is not a single-dimensional array, compiler error CS0225 occurs.


No comments:

Post a Comment