Search code examples
c#parameter-passingparametersvariadic-functionsvariadic

Why use the params keyword?


I know this is a basic question, but I couldn't find an answer.

Why use it? if you write a function or a method that's using it, when you remove it the code will still work perfectly, 100% as without it. E.g:

With params:

static public int addTwoEach(params int[] args)
{
    int sum = 0;
    foreach (var item in args)
        sum += item + 2;
    return sum;
}

Without params:

static public int addTwoEach(int[] args)
{
    int sum = 0;
    foreach (var item in args)
       sum += item + 2;
    return sum;
}

Solution

  • With params you can call your method like this:

    addTwoEach(1, 2, 3, 4, 5);
    

    Without params, you can’t.

    Additionally, you can call the method with an array as a parameter in both cases:

    addTwoEach(new int[] { 1, 2, 3, 4, 5 });
    

    That is, params allows you to use a shortcut when calling the method.

    Unrelated, you can drastically shorten your method:

    public static int addTwoEach(params int[] args)
    {
        return args.Sum() + 2 * args.Length;
    }