C# Programming/Keywords/params

From Wikibooks, open books for an open world
Jump to: navigation, search

The keyword params is used to describe when a grouping of parameters are passed to a method, but the number of parameters are not important, as they may vary. Since the number isn't important, the params keyword must be the last variable in a method signature so that the compiler can deal with the parameters which have been defined first, before dealing with the params.

Here are examples of where it will, and will not work:

// This works
public static void AddToShoppingBasket(decimal total, params string[] items)
{
  // ....
}
 
// This works
public static void AddToShoppingBasket(decimal total, int totalQuantity, params string[] items)
{
  // ....
}
 
 
// THIS DOES NOT WORK                  <-------------------->
public static void AddToShoppingBasket(params string[] items, decimal total, int totalQuantity)
{
  // ....
}

A good example of this is the String.Format method. The String.Format method allows a user to pass in a string formatted to their requirements, and then lots of parameters for the values to insert into the string. Here is an example:

public static string FormatMyString(string format, params string[] values)
{
     string myFormat = "Date: {0}, Time: {1}, WeekDay: {1}";
     return String.Format(myFormat, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), DateTime.Now.DayOfWeek);
}
 
// Output will be something like:
//
// Date: 7/8/2007, Time: 13:00, WeekDay: Tuesday;
//

The String.Format method has taken a string, and replaced the {0}, {1}, {2} with the 1st, 2nd and 3rd parameters. If the params keyword did not exist, then the String.Format() would need an infinite number of overloads to cater for each case.

public string Format(string format, string param1)
{
  // .....
}
 
public string Format(string format, string param1, string param2)
{
  // .....
}
 
public string Format(string format, string param1, string param2, string param3)
{
  // .....
}
 
public string Format(string format, string param1, string param2, string param3, string param4)
{
  // .....
}
 
public string Format(string format, string param1, string param2, string param3, string param4, string param5)
{
  // .....
}
 
// To infinitum



C# Keywords
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach
goto if implicit in int
interface internal is lock long
namespace new null object operator
out override params private protected
public readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch this
throw true try typeof uint
ulong unchecked unsafe ushort using
var virtual void volatile while
Special C# Identifiers
add alias get global partial
remove set value where yield