Parts 16

What is Params ?

Param used to specify a parameter. Param take number of argument.

Important Point 

     1. The params keyword is used to when we are not sure about number of arguments to send as a parameter. 
Ex- paramsMethod [ ]

     2. Only one param keyword is allowed and no additional parameter is permitted after param keyword in a function declaration.

Ex- paramsMethod (params object [ ] arr, int i) //Compile time error


    3. we are not sending any arguments to the defined parameter, then the length of params list will become a zero.
   
    4. We can send an arguments of specified type as a comma-separated list or an array to the declared parameter. 

Ex- paramsMethod(10, 33, 24, 50);   

Example
1



class Program  

    {  

        public void Show(params int[] val) // Params Paramater  

        {  
            for (int i=0; i<val.Length; i++)  
            {  
                Console.WriteLine(val[i]);  
            }  
        }
static void Main(string[] args)  
        {  
            Program program = new Program(); // Creating Object  
            program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length  
        }  
    }    

Example 2

class Program
    {
        static void Main(string[] args)
        {
            ParamsMethod(1, 2, "chandan""pandey");
        }

        public static void ParamsMethod(params object[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + (i < arr.Length - 1 ? ", " : ""));
            }
                Console.ReadLine();
        }
    }

If you observe above example, we are sending a comma separated list of multiple arguments of the specified type (integer) to the declared parameter in ParamsMethod function.

Explanation : In above program the object type params parameter can accept any type of data and any number of arguments.

please comment if you have any doubt  & query regarding to this topic and for another new tutorial topic just drop me a comment.