Posted by The Tallest on 11/22/2007

6 comments
Skill

C# Snippet Tutorial - The Params Keyword

Posted in:

We are going to take a quick look at another C# keyword today - the params keyword. This keyword is another one of those not well known keywords in C#, but it makes life a lot easier in certain situations - and code a lot cleaner. What does the params keyword do, you ask? Well, lets take a look.

The main use of the params keyword is to give the ability to create functions that take a variable number of arguments - often called "variadic" or "variable arity" functions. This is not a feature specific to C#, and C# is definitely not the first - although it is easier in some languages than others. C and C++ have it, in the form of the "..." syntax, and Java uses that syntax as well. Everything from scheme to javascript can do it - although as you get toward javascript the syntax becomes somewhat ugly (perhaps that is a topic for another tutorial).

But this is a tutorial about C#, not about those other languages. So here is some code:

public int Add(params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  return sum;
}

So, as you can see, you use the params keyword in the argument list. Essentially, what that argument block is saying is that it can take an arbitrary number of ints, and those ints will be presented to the internals of the function as an array of ints.

Here are some ways that you can call this function:

int ans1 = Add(1);

int ans2 = Add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int ans3 = Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int ans4 = Add();

And here are the values those result variables will hold:

ans1: 1
ans2: 55
ans3: 55
ans4: 0

So as you can see, you can call this Add function with 0 or more arguments, and you can even pass in an array (and that array gets passed straight through). While you can pass in arrays where there is a param argument, you cannot mix and match arrays and regular values at all:

int ans5 = Add(new int[] { 1, 2, 3, 4, 5}, 5, 6, 7, 8);
// Error: The best overloaded method match for 'Add(params int[])'
// has some invalid arguments

int ans6 = Add(5, 6, 7, 8, new int[] { 1, 2, 3, 4, 5 });
// Error: The best overloaded method match for 'Add(params int[])'
// has some invalid arguments

Another thing to note is that the params argument does not need to be the only argument to the function, but it does need to be the last. For instance, this is valid:

public void AddAndPrint(string str, params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  Console.WriteLine(str + sum);
}

But this is not valid at all:

public void AddAndPrint(params int[] list, string str)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  Console.WriteLine(str + sum);
}

// Error: A params parameter must be the last parameter in a formal parameter list     

You can do some cool things with the params keyword. For instance, here is an integer "fold" method:

public delegate int FoldIntDelegate(int a, int b);

public static int Fold(FoldIntDelegate fid, params int[] list)
{
  int result = 1;
  foreach (int i in list)
    result = fid(result, i);
  return result;
}

And you can call it like this:

int ans7 = Fold(new FoldIntDelegate(delegate(int a, int b) { return a * b; }),
                1, 3, 5, 7, 9));

So here we are passing in an anonymous delegate that will perform the multiplication of 2 ints and return the result, and the Fold method takes that delegate and 'folds' it over the variable number of integer arguments, giving a cumulative multiplication total, in this case resulting in the answer 945.

Well, that is it for the params keyword in C#. If you have any other questions about its use, feel free to drop a comment below.

Cyr1dian
02/07/2008 - 10:26

What is the point of using params over just passing some type of list?

reply

Rainer Gustin
03/10/2008 - 02:16

Good question...
Relatively little benefit for a list of the same types but the string.Format() function allows mixed types.
Here is example code.

//ErrorBox("Copying file {0} to {1} failed", "a.txt", "b.txt");

static void ErrorBox(string err, params object[] list)
{
  string errText = string.Format(err, list);
  MessageBox.Show(errText, "Critical Error",
      MessageBoxButtons.OK);

  //You can also iterate through the params list
  //yourself and depending on the type do something.
  foreach (object item in list)
  {
    if (item is string)
    {
      string s = (string)item;
    }
  }
}

reply

Nagaveni
04/29/2008 - 05:47

in java how to use the params keywords plz tell me i want to get the parameter names

reply

Rocon
09/04/2008 - 02:55

above tutorials are good.
can you tell me about this textarea which is resizeable.
please...
roconuiu@yahoo.com

reply

The Tallest
09/04/2008 - 06:09

Rocon, you probably want to check out this article here, which explains how to add our resizeable textbox to wordpress.

reply

Bhupendra
12/24/2008 - 23:42

your example for param keyword is
difficult to understand
please give a simple example explaining param
your early reply will be very helpful to me…………

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.