Parameters#

Parameters are passed by value; the rules for value and reference types are described in Type System.

ModifierPassed byDefinite AssignmentNotes
(none)valuebefore the call
refreferencebefore the call
inreferencebefore the callread-only
outreferencebefore returning control

Furthermore, you can pass parameters by reference in three different ways.

Passing by Reference (ref)#

Passing a parameter using ref allows the method to read and write to the passed variable. Passing a reference type by reference allows the reference itself to be changed from within the method.

int x = 8;
Foo(ref x);
Console.WriteLine(x); // outputs 9

static void Foo(ref int p)
{
    p = p + 1;
    Console.WriteLine(p); // outputs 9
}

Output Parameters (out)#

The out modifier works similarly, with the difference that the variable must be assigned within the method, and it can be uninitialized before the method call. This is one way to return more than one value from a method. Furthermore, if you are not interested in one of the output values, you can discard it using the _ symbol.

string[] firstNames; string lastName;
GetFirstAndLastNames("Tim Berners Lee",
                     out firstNames, out lastName);
GetFirstAndLastNames("John Fitzgerald Kennedy",
                     out var firsts, out string last);
GetFirstAndLastNames("Julius Robert Oppenheimer",
                     out firsts, out _); // last parameter discarded
                     
static void GetFirstAndLastNames(string name,
                                 out string[] firstNames,
                                 out string lastName)
{
    string[] words = name.Split(' ');
    firstNames = words[..^1];
    lastName = words[^1];
}

Input Parameters (in)#

The in modifier also works similarly; the difference here is that the passed parameter becomes read-only within the method body.

using System.Numerics;

Matrix4x4 A = Matrix4x4.CreateRotationX(MathF.PI / 2);
Matrix4x4 B = Matrix4x4.CreateRotationY(MathF.PI / 4);
Multiply(in A, in B, out var result);
Console.WriteLine(result);

static void Multiply(in Matrix4x4 a,
                     in Matrix4x4 b,
                     out Matrix4x4 result)
{
    // a = Matrix4x4.Identity; // Compilation error: 'a' is read-only
    result = a * b;
}

Variable Number of Parameters (params)#

The params keyword allows a variable number of arguments to be passed to a method. It can only be used for the last parameter. Traditionally, its type is a single-dimensional array (since C# 13, other collection types are allowed as well); the compiler implicitly creates an array from the arguments provided for the params parameter.

using System.Text;

var s1 = Concat("The", "Quick", "Brown", "Fox");
var s2 = Concat("Jumps", "Over", "The", "Lazy", "Dog");
Console.WriteLine(Concat(s1, s2));
Concat("This function accepts at least 1 parameter");

static string Concat(string str, params string[] strings)
{
    StringBuilder sb = new StringBuilder(str);
    foreach (string s in strings)
        sb.Append(s);
    return sb.ToString();
}

params Collections (C# 13)#

Since C# 13, the type of a params parameter can also be Span<T>, ReadOnlySpan<T>, a collection interface (e.g., IEnumerable<T>, IReadOnlyList<T>, IList<T>) or a collection type (e.g., List<T>). The most useful is params ReadOnlySpan<T> (ReadOnlySpan<T> is a read-only view of a contiguous region of memory): the compiler can place the arguments on the stack, so - unlike with params T[] - no array is allocated on the heap on each call. If both overloads exist, the compiler prefers the span one. Since .NET 9, many library methods (e.g., string.Join, string.Concat, Path.Combine, Task.WhenAll) have such overloads, so existing code avoids these allocations just by being recompiled.

Console.WriteLine(Sum(1, 2, 3)); // 6
Console.WriteLine(Sum());        // 0
PrintAll("a", "b", "c");         // a, b, c
PrintAll(["x", "y"]);            // x, y - a collection can also be passed directly

static int Sum(params ReadOnlySpan<int> numbers) // no array is allocated
{
    int sum = 0;
    foreach (int n in numbers)
        sum += n;
    return sum;
}

static void PrintAll(params IEnumerable<string> items)
{
    Console.WriteLine(string.Join(", ", items));
}

Optional Parameters and Named Arguments#

Parameters in C# can have default values. The default value must be a compile-time constant. All default parameters must be defined after any required parameters. If there is a need to omit some optional parameters, you can specify which ones you want to assign a value to by using named arguments.

void ExampleMethod(int required,
                   string optionalstr = "default",
                   int optionalint = 10) {}
ExampleMethod(3, "parameter", 7);
ExampleMethod(3, "parameter");
ExampleMethod(3);
ExampleMethod(3, optionalint: 4);