Variable Arguments (Varargs) in C#

CsharpProgrammingServer Side Programming

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

Let us see an example to multiply integers. We have used params keyword to accept any number of int values −

static int Multiply(params int[] b)

The above allows us to find multiplication of numbers with one as well as two int values. The fllowing calls the same function with multiple values −

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

Let us see the complete code to understand how variable arguments 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;
   }
}
raja
Published on 13-Aug-2018 17:39:09
Advertisements