C# Programming/Keywords/params
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 many 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 | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Special C# Identifiers (Contextual Keywords) | |||||||||||||||
| |||||||||||||||
Contextual Keywords (Used in Queries) | |||||||||||||||
|