skip to content

In C#, what does a `params string?[]? names` parameter receive for `Describe()`, `Describe(null)`, `Describe((string?)null)` and an existing array?

level: middleimportance: should knowfreq 52%

answer

  1. normal form is tried first
  2. one shared empty array
  3. a bare null converts to the array
  4. a typed null becomes an element
  5. the caller's array, not a copy

basics

~10 s

Describe() gets an empty array (the shared Array.Empty<string?>() instance), Describe(null) gets a null array, Describe((string?)null) gets a one-element array holding null, and an existing array is passed as is, so writes reach the caller.

solid answer

~50 s

A `params` parameter is an ordinary array parameter that the compiler can also fill for you. If the argument already converts to the array type, which is true of an existing `string?[]` and of the `null` literal, the call uses the **normal form** and passes that value through: `Describe(null)` gives `names == null`, and `Describe(mine)` hands over the caller's own array, so writes to it are visible to the caller. Otherwise the compiler uses the **expanded form** and builds a new array from the arguments, which is why `Describe((string?)null)` gets a one-element array. With no arguments it passes `Array.Empty<string?>()`, one cached instance. A robust method checks for `null`, never writes into the array, and copies it before storing it. If the parameter is declared non-nullable, `params string[] names`, `Describe(null)` warns CS8625 with nullable reference types enabled.

code

csharp · 22 lines
csharp
string[] mine = ["region", "total"];

Columns.Describe();
Columns.Describe("region", "total");
Columns.Describe(mine);
Console.WriteLine($"caller's array now: [{string.Join(", ", mine)}]");
Columns.Describe((string?)null);
Columns.Describe(null);

static class Columns
{
    public static void Describe(params string?[]? names)
    {
        if (names is null)
        {
            Console.WriteLine("names is null");
            return;
        }
        Console.WriteLine($"Length {names.Length}");
        if (names.Length > 0) names[0] = "CHANGED";
    }
}

go deeper

for a junior

Recall that params lets callers pass a list of values or nothing at all, and that it must be the last parameter.

for a middle

Explain the normal and expanded forms, and predict what the array holds for no arguments, a bare null, a typed null and an existing array.

for a senior

Show the production habits: null checks despite annotations, never mutating or storing a params array without copying, and spotting per-call allocations on hot paths.

for a principal

Weigh whether a public API should offer params at all, given aliasing, null handling and allocation, against callers that already hold an array or span.

## What `params` declares The `params` modifier marks the **last** parameter of a method as one that callers can fill with a comma-separated list of arguments. For a column formatter in a reporting tool: ```csharp static void Describe(params string?[]? names) { /* ... */ } ``` callers can write `Describe("region", "total")` instead of `Describe(new[] { "region", "total" })`. The compiler enforces a short list of rules on the declaration: - It must be the last parameter (CS0231) and a method can have only one. - It cannot have a default value (CS1751) and cannot be `ref`, `out` or `in` (CS1611). - It may follow optional parameters: `void Log(string format = "", params object[] args)` compiles. - Until C# 13 it had to be a single-dimensional array. C# 13 also allows spans and other collection types; that change is covered in the lesson on params collections. Inside the method, `names` is simply a `string?[]?` value. Everything interesting happens at the call site. ## Normal form first, expanded form second For each call the compiler first tries the **normal form**: the method exactly as declared, with one array argument. Only if that does not apply does it try the **expanded form**, which builds a new array from the arguments. The detailed rules that pick between two different overloads belong to the lesson on overload resolution; for a single method the effect is easy to predict: | Call | Form used | What `names` holds | |---|---|---| | `Describe()` | expanded, zero elements | `Array.Empty<string?>()`, length 0 | | `Describe("region", "total")` | expanded | a new array of length 2 | | `Describe(mine)` | normal | the caller's own array object | | `Describe(null)` | normal | `null` | | `Describe((string?)null)` | expanded | a new array holding one `null` | The fourth row surprises people. The `null` literal converts to the array type, so the normal form applies and the method receives a null reference instead of an array. Code that reads `names.Length` without a check throws `NullReferenceException` inside the method. The same reasoning applies to any argument whose static type is the array type: a variable declared `string?[]? maybe` that happens to hold null is passed straight through as a null array. To pass one null element, cast it (`(string?)null`) or pass a one-element array or collection expression yourself. With nullable reference types enabled, the declared annotation decides whether the compiler warns. If the parameter is `params string[] names`, then `Describe(null)` produces warning CS8625, "Cannot convert null literal to non-nullable reference type". The warning does not stop the call; at run time `names` is still null. ## The caller's array is shared In the normal form nothing is copied. If the caller passes `mine` and the method assigns `names[0] = "CHANGED"`, the caller sees the change afterwards. The .NET design guidelines advise against `params` arrays for methods that modify the array, because the array is often a temporary built at the call site, so the change is silently lost. With a normal-form call the opposite happens: the change lands in the caller's data. A related trap involves `params object[]`. Because `string[]` converts to `object[]` through array covariance, `Items(new string[] { "a", "b" })` uses the normal form and `items.Length` is 2. Casting the array to `object` turns it into a single element of length 1. ## What each call allocates Each expanded call with one or more arguments allocates a **new array** on the heap, every time it runs. A zero-argument call does not: the compiler emits `Array.Empty<T>()`, which returns the same cached empty array, so two zero-argument calls receive the same reference. On a hot path, a `params` array therefore costs one allocation per call with arguments; avoiding that allocation was one motivation for C# 13's `params ReadOnlySpan<T>`. ## Habits that hold up in review 1. Annotate the parameter honestly: `params string?[]?` if callers may pass null, otherwise `params string[]` so they get CS8625. 2. Check for `null` before reading the array, even with nullable annotations, because they are warnings, not run-time checks. 3. Never write into a `params` array; copy it with `ToArray()` or a collection expression before storing it in a field. 4. When a caller means "one null element", make it explicit with a cast so a reviewer does not have to remember the normal-form rule.

  • Why does Describe(null) fail inside the method rather than at the call when the parameter is params string[] names?
    The call is legal: the `null` literal converts to `string[]`, so the normal form passes a null array. With nullable reference types on you only get warning CS8625. The failure comes later, when the method reads `names.Length` and throws `NullReferenceException`.
  • For a method declared Items(params object[] items), what is items.Length after Items(new string[] { "a", "b" })?
    Two. Array covariance converts `string[]` to `object[]`, so the normal form applies and the string array itself becomes `items`. Writing `Items((object)new string[] { "a", "b" })` forces the expanded form, and `items` is a new one-element array holding the string array.

  • Describe(null) passes an array that contains one null element.
  • Calling a params method with no arguments passes null.
  • params always copies the caller's array, so writes inside stay local.
  • Every zero-argument call allocates a new empty array.
  • A params parameter can take a default value such as null.