Easy Tutorial
❮ Csharp Inheritance Home ❯

C# Parameter Arrays

C# Arrays

Sometimes, when declaring a method, you cannot determine the number of parameters to pass to the function as arguments. C# parameter arrays solve this problem, and are commonly used to pass an unknown number of parameters to a function.

The params Keyword

When using an array as a formal parameter, C# provides the params keyword, which allows the method to be called either with an array argument or with a sequence of array elements. The format for using params is:

public ReturnType MethodName(params TypeName[] ArrayName)

Example

The following example demonstrates how to use parameter arrays:

using System;

namespace ArrayApplication
{
    class ParamArray
    {
        public int AddElements(params int[] arr)
        {
            int sum = 0;
            foreach (int i in arr)
            {
                sum += i;
            }
            return sum;
        }
    }

    class TestClass
    {
        static void Main(string[] args)
        {
            ParamArray app = new ParamArray();
            int sum = app.AddElements(512, 720, 250, 567, 889);
            Console.WriteLine("The total sum is: {0}", sum);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

The total sum is: 2938

C# Arrays

❮ Csharp Inheritance Home ❯