Home >Backend Development >C#.Net Tutorial >Variable parameters (Varargs) in C#

Variable parameters (Varargs) in C#

WBOY
WBOYforward
2023-09-09 12:57:021298browse

C# 中的变量参数 (Varargs)

Use the param keyword in C# to get variable parameters.

Let’s look at an example of multiplying integers. We use the params keyword to accept any number of int values ​​-

static int Multiply(params int[] b)

The above code allows us to find the numerical multiplication of one or two int values. The following calls the same function with multiple values ​​-

int mulVal1 = Multiply(5);
int mulVal2 = Multiply(5, 10);

Let’s see the complete code to understand how variable parameters work in C# -

Example

using System;

class Program {
   static void Main() {
      int mulVal1 = Multiply(5);
      int mulVal2 = Multiply(5, 10);

      Console.WriteLine(mulVal1);
      Console.WriteLine(mulVal2);
   }

   static int Multiply(params int[] b) {
      int mul =1;
      foreach (int a in b) {
         mul = mul*a;
      }
      return mul;
   }
}

The above is the detailed content of Variable parameters (Varargs) 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