params arrays

suggest change

The 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

  1. Position: The params parameter must be the last parameter in the method's parameter list.
  2. Cardinality: A method declaration can have at most one params parameter.
  3. Type: In C# 12 and earlier, the parameter type must be a single-dimensional array (T[]).
  4. Modifiers: The params keyword cannot be combined with ref, in, or out.
  5. No Default Values: A params parameter cannot declare a default parameter value (e.g., params int[] nums = null is 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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents