params arrays
suggest changeThe params keyword allows a method parameter to accept a variable number of arguments. Callers can pass a comma-separated list of arguments of the specified element type, an array instance, or no arguments at all.
1. Syntax and Language Rules
To declare a parameter array, place the params modifier before a single-dimensional array parameter:
public static void PrintNames(string prefix, params string[] names)
{
Console.WriteLine($"Prefix: {prefix}");
Console.WriteLine($"Total names: {names.Length}");
foreach (string name in names)
{
Console.WriteLine($" - {name}");
}
}
Compiler Rules
- Position: The
paramsparameter must be the last parameter in the method's parameter list. - Cardinality: A method declaration can have at most one
paramsparameter. - Type: In C# 12 and earlier, the parameter type must be a single-dimensional array (
T[]). - Modifiers: The
paramskeyword cannot be combined withref,in, orout. - No Default Values: A
paramsparameter cannot declare a default parameter value (e.g.,params int[] nums = nullis illegal).
2. Calling Methods with params
Methods declaring params can be invoked in two forms: expanded form and unexpanded form.
using System;
class Program
{
static int Sum(params int[] numbers)
{
if (numbers == null) return 0;
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static void Main()
{
// 1. Expanded form: Comma-separated list of elements
// The compiler automatically generates: Sum(new int[] { 1, 2, 3, 4, 5 })
int s1 = Sum(1, 2, 3, 4, 5);
// 2. Unexpanded form: Explicit array passed directly
int[] existingArray = new int[] { 10, 20, 30 };
int s2 = Sum(existingArray);
// 3. Zero arguments:
// The compiler generates: Sum(new int[0]) (or Array.Empty<int>())
int s3 = Sum();
Console.WriteLine($"s1: {s1}, s2: {s2}, s3: {s3}");
}
}
The null Argument Pitfall
When passing null to a method taking params object[] or params string[], overload resolution treats null as the entire array reference rather than a single-element array containing null:
static void Display(params string[] items)
{
if (items == null)
{
Console.WriteLine("items array is null!");
}
else
{
Console.WriteLine($"Length: {items.Length}");
}
}
Display(null); // Output: "items array is null!"
Display((string)null); // Output: "Length: 1" (single null element: new string[] { null })
Display(new string[] { null }); // Output: "Length: 1"
To avoid NullReferenceException, always defensively guard against a null array in your method implementation:
public static void Process(params string[] values)
{
values ??= Array.Empty<string>();
// Safe to use values.Length or iterate...
}
3. Overload Resolution and Performance
When you invoke a method using the expanded form (e.g., Log("msg", a, b)), the C# compiler allocates a new temporary array on the managed heap. In high-frequency, performance-sensitive code, this causes unnecessary garbage collector allocations.
To eliminate allocations for common use cases, framework APIs use specialized overloads alongside the params catch-all:
public class Logger
{
// Fast path: Zero array allocation
public void Log(string message) { /* ... */ }
// Fast path: 1 argument (no array allocation)
public void Log(string message, object arg1) { /* ... */ }
// Fast path: 2 arguments (no array allocation)
public void Log(string message, object arg1, object arg2) { /* ... */ }
// Fallback path: 3 or more arguments (allocates array)
public void Log(string message, params object[] args) { /* ... */ }
}
The C# compiler always prefers a specific non-params signature over the expanded params form when an exact parameter count matches.
4. Modern C# 13: params Collections and ReadOnlySpan<T>
Beginning with C# 13 (.NET 9), the params modifier is no longer restricted to arrays. It now supports any recognized collection type, including:
ReadOnlySpan<T>andSpan<T>IEnumerable<T>,IReadOnlyList<T>,IList<T>- Concrete collection types like
List<T>
Zero-Allocation High Performance with ReadOnlySpan<T>
Using params ReadOnlySpan<T>, the compiler allocates the arguments directly on the stack or embeds them into assembly data without allocating a heap array:
// C# 13+ zero-allocation params
public static int CalculateMax(params ReadOnlySpan<int> values)
{
if (values.IsEmpty) throw new ArgumentException("At least one value required.");
int max = values[0];
for (int i = 1; i < values.Length; i++)
{
if (values[i] > max) max = values[i];
}
return max;
}
// Invocation without heap allocation:
int highest = CalculateMax(12, 45, 9, 87, 23);
5. Summary and Best Practices
- Validate against
null: Callers can pass an explicitnull, so guard withargs ??= Array.Empty<T>(). - Provide overloads for hot paths: If a method is called frequently in tight loops, provide 1-argument and 2-argument overloads to avoid heap array allocations.
- Adopt
params ReadOnlySpan<T>in modern .NET: When targeting .NET 9+ / C# 13+, preferparams ReadOnlySpan<T>for read-only element access to get maximum performance and zero garbage collection overhead. - Do not use for required arguments: If a method requires at least one item, make the first parameter explicit:
// Guarantees at compile time that at least one item is provided public void ProcessItems(Item first, params Item[] others) { ... }