The params Keyword

The params keyword allows you to pass in a variable number of parameters of the same type to a method. What the method receives is an array of that type.

In the next example, you create a method, DisplayVals( ) , that takes a variable number of integer arguments:

    public void DisplayVals(params int[] intVals)

You are free to iterate over the array as you would over any other array of integers:

    foreach (int i in intVals)
    {
       Console.WriteLine("DisplayVals {0}",i);
    }

The calling method, however, need not explicitly create an array: it can simply pass in integers, and the compiler will assemble the parameters into an array for the DisplayVals( ) method:

    t.DisplayVals(5,6,7,8);

You are free to pass in an array if you prefer:

    int [] explicitArray = new int[5] {1,2,3,4,5};
    t.DisplayVals(explicitArray);

Warning

You can only use one params argument for each method you create, and the params argument must be the last argument in the method’s signature.

Example 10-3 illustrates using the params keyword.

Example 10-3. Using the params keyword

using System;

namespace UsingParams
{
   public class Tester
   {
      static void Main( )
      {
         Tester t = new Tester( );
         t.DisplayVals(5,6,7,8);
         int [] explicitArray = new int[] {1,2,3,4,5};
         t.DisplayVals(explicitArray);
      }

      public void DisplayVals(params int[] intVals)
      {
         foreach (int i in intVals)
         {
            Console.WriteLine("DisplayVals {0}",i);
         }
      }
   }
}

The output looks like this:

    DisplayVals 5
    DisplayVals 6
    DisplayVals 7
    DisplayVals 8
    DisplayVals 1
    DisplayVals 2
    DisplayVals 3
    DisplayVals 4
    DisplayVals 5
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset