How to pass the variable number of arguments in C#?

Solution

C# provides param keyword, which allows to pass the variable number of arguments in a method. We can pass comma (,) separated list of specified type while calling the method.

Length of param argument will be zero if we do not pass any argument while calling the method.

Example

    
   class Program
    {
        static void Main(string[] args)
        {
            // Passing 4 aarguments
            PrintNames("Ashish", "Amit", "User1", "User2");

            //passing 2 arhuments
            PrintNames("Ashish", "Shukla");

            //calling without passing any arguments
            PrintNames();
            Console.ReadLine();
        }

        static void PrintNames(params string[] names)
        {
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
        }
   }

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media