Home  >  Article  >  Backend Development  >  Why do we use params keyword in C#?

Why do we use params keyword in C#?

WBOY
WBOYforward
2023-09-21 17:53:041065browse

为什么我们在 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();
      }
   }
}

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!

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