Passing Arrays to methods using params keyword

Program

using System;

namespace ClassRoomSamples
{
    class Demo12PassingArraysUsingParamsKeyword
    {
        static void Main(string[] args)
        {
            int[] salPerAnnum = new int[5] { 10, 20, 15, 14, 12 };
            displaySalary1(salPerAnnum);
            displaySalary2(10, 20, 15, 14, 12);
            displaySalary3("CTS", 11, 15, 20);

            //displaySalary4(100, 200, 150, 140, 120, "UST"); 
            //this is not allowed... a collection of values you are 
            //passing to params array will be at last not in the beginning

            Console.ReadKey();
        }

        public static void displaySalary1(int[] sal)
        {
            Console.WriteLine("By Display Salary1");
            foreach (int x in sal)
            {
                Console.WriteLine(x);
            }
        }

        public static void displaySalary2(params int[] sal)
        {
            Console.WriteLine("By Display Salary 2");
            foreach (int x in sal)
            {
                Console.WriteLine(x);
            }
        }

        public static void displaySalary3(string compName, params int[]                                                                         sal)
        {
            Console.WriteLine("Salary of " + compName);
            foreach (int x in sal)
            {
                Console.WriteLine(x);
            }
        }

        //params array entry should appear at last in the arguments list 
        //not in first level, so the following method declaration is wrong

        /*public static void displaySalary4(params int[] sal, string                                                                       compName)
        {
            Console.WriteLine("Salary of " + compName);
            foreach (int x in sal)
            {
                Console.WriteLine(x);
            }
        }*/
    }
}


Output

By Display Salary1
10
20
15
14
12

By Display Salary 2
10
20
15
14
12

Salary of CTS
11
15
20

No comments:

Post a Comment