About
In this code snippet, we will learn how to use the params keyword in C#.
The params keyword is used to define an array of input parameters for a method. Instead of explicitly defining every single one we can just pass in an array of parameters. As you can imagine when you have a lot of parameters this becomes very useful.
Let’s see the code example below.
Code:
using System;
namespace Params
{
class Program
{
static void Main(string[] args)
{
Add(5,10,20,1,7);
Console.ReadLine();
}
//Params is used to define an array of input parameters.
//As you can imagine this would require a lot more work if every parameter would have to be defined.
//Also for every different number of parameters we would have to define a separate overloaded method.
public static void Add(params int[] numbers)
{
int sum = 0;
foreach (var item in numbers)
{
sum += item;
}
Console.WriteLine(sum);
}
}
}





