Question

Assume I define a method like this:

public static void ListInts(int[] inVals)
{
    for (int i = 0; i < inVals.Length; i++)
    {
         Console.WriteLine("{0}", inVals[i]);
    } 
}

If I try call it like this, obviously i'm getting an error and code will not compile:

ListInts();

Method 'ListInts' has one parameter(s) but is invoked with 0 arguments

But when i change method definition like this:

public static void ListInts(params int[] inVals)
{
    for (int i = 0; i < inVals.Length; i++)
    {
         Console.WriteLine("{0}", inVals[i]);
    } 
}

There is no error.I'm curious why this is happening ? And why second code is compiling without any errors? What happens behind the scenes when we use params keyword ?

Was it helpful?

Solution

You could have easily search for the reason in the documentation.

From MSDN:

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration or an array of arguments of the specified type. You also can send no arguments. If you send no arguments, the length of the params list is zero. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

OTHER TIPS

The params keyword makes a function into a variadic function. Variadic functions can take anywhere from 0 to (in theory) infinite arguments. So that is why your code compiles. The string.Format function is a classical example of a variadic function.

If you want to create a variadic function that has to accept at least one parameter, you can do the following (in C#):

   int methodname(int arg1, param int[] restOfArgs) {}

At which point you will be forced to give at least one argument to the function

MSDN link

http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

By using the params keyword, you can specify a method parameter that takes a variable number of arguments.You can send a comma-separated list of arguments of the type specified in the parameter declaration or an array of arguments of the specified type. You also can send no arguments. If you send no arguments, the length of the params list is zero.No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top