Why do we use params keyword in C#?

WBOY
Release: 2023-09-21 17:53:04
forward
1111 people have browsed it

为什么我们在 C# 中使用 params 关键字?

When declaring a method, if you are not sure about the number of parameters to be passed as parameters, you can use C#'s param array.

The following is a complete example for learning how to implement param in C#:

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

The above is the detailed content of Why do we use params keyword in C#?. 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