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

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

WBOY
Release: 2023-08-29 17:45:07
forward
1385 people have browsed it

如何在 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) {
}
Copy after login

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();
      }
   }
}
Copy after login

Output

The sum is: 1620
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template