April 3, 2011

Variable Parameter passing in C#

How We can write  a method that accepts a variable number of parameters?


Answer :The params keyword can be used for  a method parameter that is an array.  When the method is invoked, the elements of the array can be passed as a comma separated list.


Below is the sample code




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class Program
    {


        static void TestVarArg(params int[] args)
        {
            foreach (int arg in args)
            {
                Console.WriteLine(arg);
            }
        }




        static void TestVarArgString(params string [] args)
        {
            foreach (string  arg in args)
            {
                Console.WriteLine(arg);
            }
        }




        static void Main(string[] args)
        {
            TestVarArg(1, 2, 3);
            Console.WriteLine();


            TestVarArg(3, 4, 5,6,7);


            Console.WriteLine();


            string[] names = new string[3] { "Test1", "Test2", "Test3" };
            TestVarArgString(names);


            Console.WriteLine();


            TestVarArgString("Test4", "Test5");


        }
    }
}


See the o/p 


No comments:

Post a Comment