C#: Method with Arbitrary or Variable Number of Parameters


Normally when I create a method that needs to accept an arbitrary or variable number of parameters or arguments I just accept an array of values. This works great but it does require you to instantiate a new array and populate it every time you want to call the method. Not a big deal but as you can see below it makes the code a bit messy.

static void Main(string[] args)
{
    CountParameters(new int[] { });
    CountParameters(new int[] { 5, 3, 6 });
    CountParameters(new int[] { 1, 2, 3, 4 });
    CountParameters(new int[] { 8, 3, 78, 234, 2, 56, 87 });
}

public static void CountParameters(int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

// Output
// ------
// 0 parameters passed in
// 3 parameters passed in
// 4 parameters passed in
// 7 parameters passed in

But, if you simply add the ‘params’ keyword before the parameter definition, this allows you to call the method by just specifying a comma delimited list of arguments.

static void Main(string[] args)
{
    CountParameters();
    CountParameters(5, 3, 6);
    CountParameters(1, 2, 3, 4);
    CountParameters(8, 3, 78, 234, 2, 56, 87);
}

public static void CountParameters(params int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

// Output
// ------
// 0 parameters passed in
// 3 parameters passed in
// 4 parameters passed in
// 7 parameters passed in

You can also specify other parameters for the method but the parameter with the ‘params’ keyword must be the last parameter definition. Further you can only add the ‘params’ keyword to one parameter in the list of parameters. More information about the ‘params’ keyword can be found here.

Interestingly, if you look at the disassembly of the second code segment above, you will see the following:

private static void Main(string[] args)
{
    CountParameters(new int[0]);
    CountParameters(new int[] { 5, 3, 6 });
    CountParameters(new int[] { 1, 2, 3, 4 });
    CountParameters(new int[] { 8, 3, 0x4e, 0xea, 2, 0x38, 0x57 });
    Console.ReadLine();
}

public static void CountParameters(params int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

It simply instantiates a new array of integers and passes it to the CountParameters method as we did in the first approach. So this is obviously just a way to make your code a bit more readable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: