Home  >  Article  >  Backend Development  >  How to pass parameters using param array in C# method?

How to pass parameters using param array in C# method?

WBOY
WBOYforward
2023-08-29 17:45:071357browse

如何在 C# 方法中使用 param 数组传递参数?

When declaring a method, you are not sure of the number of arguments passed as formal parameters. This is where the C# parameter array (or parameter array) comes in handy.

This is how to use parameters -

public int AddElements(params int[] arr) {
}

Here is the complete example -

Example

using System;

namespace Program {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;

         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }

   class Demo {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(300, 250, 350, 600, 120);

         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}

Output

The sum is: 1620

The above is the detailed content of How to pass parameters using param array in C# method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete