C # parameter array


Release date:2023-08-30 Update date:2023-10-13 Editor:admin View counts:239

Label:

C # parameter array

Sometimes, when you declare a method, you cannot determine the number of parameters to pass to the function as arguments. The C # parameter array solves this problem, which is usually used to pass an unknown number of arguments to the function.

Params keyword

When using arrays as formal parameters, C # provides params keyword, which allows you to pass either an array argument or an array of elements when calling a method with an array of formal parameters. params format of the use is:

Public return type method name (params type name [] array name)

Example

The following example shows how to use a parameter array:

Example

using System;
namespace ArrayApplication
{
   class ParamArray
   {
      public int AddElements(params int[] arr)
      {
         int sum = 0;
         foreach (int i in arr)
         {
            sum += i;
         }
         return sum;
      }
   }

   class TestClass
   {
      static void Main(string[] args)
      {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         Console.WriteLine("The total is: {0}", sum);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

The total is: 2938

Powered by TorCMS (https://github.com/bukun/TorCMS).