C# Params Keyword and its Use

During the course of your programming career you may encounter situations where you need to have a method that can accept ‘n’ number of parameters at run time. In such cases, C# params keyword can be quite helpful.

Params keyword in C# allows a method or a constructor to receive variable number of parameters. When params is used then the compiler converts the arguments passed to a method into a temporary array. This temporary array then can be used in the receiving method to perform some operation on its elements.

When using params you can pass a comma-separated list of arguments of the type specified in the method signature or an array of arguments of the specified type. It also gives you the flexibility to send no arguments to the method and in such a case the length of the params list is zero.

How MSDN define C# params keyword:

By using the params keyword, you can specify a method parameter that takes a variable number of arguments.

Now let’s see an example of how params keyword is used.

C# Params

Example of using params keyword in a method:

Let’s consider we want to write a method in C# that can concatenate any number of strings arguments passed to it.

So, we will write it as:

class Program
{
    static void Main(string[] args)
    {
        //Passing param arguments as comma seperated strings
        Console.WriteLine(Concatenate("Dogs", " ", "are", " ", "cute", " ", "pets", "!"));

        //Pasing param arguments as a string array
        Console.WriteLine(Concatenate(new string[] { "I", " ", "like", " ", "dogs","." }));

        Console.ReadKey();
    }

    private static string Concatenate(params string[] inputPrameters)
    {
        StringBuilder resultant = new StringBuilder();

        //Iterating the parameters and apending them in the resultant
        foreach (var input in inputPrameters)
        {
            resultant.Append(input);
        }
        return resultant.ToString();
    }
} 

Output:
Dogs are cute pets!
I like dogs.

Explaining the code in above example:

In the above code sample, we have a method ‘Concatenate’ that takes in a params string array as an input parameter and returns a string. Inside the method we have a foreach loop that iterates over the input parameters and appends. Finally we have a return statement that returns the resultant string.

In the Main, we have called the ‘Concatenate’ method twice, once with a comma separated list of string arguments and once with a string array as an argument. Both these are valid ways to pass arguments to a method that uses params.

Some Important Points about C# params:

Below are some important points about params:

  • You can only have a params argument at the end of a declaration list in a method.
  • You can only have a single params keyword in a method signature.
  • Params have good flexibility they allow you to send no arguments to the method.
  • The best examples of methods using params include the string.Concat and string.Format methods.
  • Params can have a slight performance overhead (we will discuss this later in the article), so it is best to avoid them in performance-critical applications.

Why params cause performance overhead:

Now let’s have a look at another method that makes use of the params keyword to sum the supplied arguments.

private static int SumAllParams(params int[] inputPrams)
{
    int num = 0;
   //Iterating the parameters and adding them
    foreach (var input in inputPrams)
    {
        num += input
    }
    return num;
}

To use this method you can call it like:

int result = SumAllParams(1,2,3,4,5);

Internally, when compiler encounters a method with params keyword called like this, it converts the call into the below form:

int result = SumAllParams(new int[] {1,2,3,4,5});

As you can see, as soon as a params method call is encountered, the parameters are put into a new array of matching type. These new arrays are created on the managed heap and the value of method arguments are copied as array elements.

This is slower than pushing parameters onto the evaluation stack. And apart from this, params keyword results in more intermediate language instructions and allocations thereby making it slightly slower than regular method invocations. And hence it is best not to use params keyword in the methods that are highly performance critical.

Note: Please note that generally methods use evaluation stack for invocation rather than managed heap and hence are much faster.

An Important fact about params keyword:

Let’s understand this fact with an example below:

class Program
{
    static void Main(string[] args)
    {
       
        Console.WriteLine("Result {0}",SumAllParams(1, 2, 3));
        Console.WriteLine("Result {0}", SumAllParams(1, 2));

        Console.ReadKey();
    }

    private static int SumAllParams(params int[] inputPrams)
    {
        Console.Write("Inside Method with param - ");
        int num = 0;

        //Iterating the parameters and adding them
        foreach (var input in inputPrams)
        {
            num += input;
        }

        return num;
    }

    private static int SumAllParams(int a , int b)
    {
        Console.Write("Inside Non Param Method - ");
        return a + b;
    }
}

In the above example, we have two overloads of a method ‘SumAllParams’. One of the overloads of the method takes a param integer array as an input, adds its elements, and returns the output, while the other overload only takes two integer parameters and returns their sum as the resultant. Till this point everything looks quite simple.

Now, if you see inside the Main, we have called the method ‘SumAllParams’ twice. In the first call we have supplied it 3 integers and it will obviously invoke the overload that takes the params int array as input. But in second call we have passed it two integers. Can you guess which overload will be called time?

Okay! With no more delays, here are the results:

Output:Example-Params-Result

So, why this happened?

The reason behind this is – The C# compilers have a preference for methods with non params parameters. When you use a params keyword it tells the compiler to apply an instance of System.ParamArrayAttribute to the method parameters.

When C# compiler encounters a call to a method, firstly it checks all the methods with the specified name, where no ParamArray attribute is applied. If there exists such a method that can accept the call, then the compiler generates the necessary code to call that method.

If it could not find such a method, then it looks for the methods that have ParamArray attribute to see whether they can satisfy the call or not. If it finds such a method then it emits the code to call that method.

So, in our case during the first call compiler searches for any non param methods that accepts three integer parameters, but since there is no such method so it allowed the call to be taken up by the method with params keyword. But in the second statement it was able to find a non param method with same signature and hence it didn’t allow the call to be passed to the method with params keyword.

Conclusion:

Params keyword makes your code easier to read and understand but as all good things come at price, and params is no different. It comes at the cost of slight performance reduction while method invocations. I would not suggest you to blindly ignore params keyword and go for its alternatives because of the performance overhead associated with it, but instead I would say run tests, compare execution times and then you will be able to understand what is good for your code and what is not.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>