skip to content

Method Calls

How C# passes arguments and resolves calls: ref, out and in, optional and named arguments, params, overloads and local functions. Interviewers test call-site rules.

on this pageshow

explore

questions

22

In C#, how do you pass only a buffer size to `Export(string path, bool overwrite = false, int bufferSize = 4096)`, and which calls fail?

level: juniorimportance: must knowfreq 72%

answer

  1. skip by name, not by comma
  2. optional parameters come last
  3. defaults must be constants
  4. named in its own position
  5. written order of evaluation

basics

~20 s

A named argument skips the gap: Export("q3.csv", bufferSize: 8192) leaves overwrite at false. The compiler rejects an empty comma slot (CS0839), an out-of-position named argument followed by a positional one (CS8323), and unknown or repeated names.

solid answer

~40 s

Optional parameters must follow every required one (CS1737 otherwise), and each default must be a compile-time constant, `new S()` or `default(S)` for a value type, or `null` (CS1736 otherwise). To skip `overwrite`, name what you pass: `Export("q3.csv", bufferSize: 8192)`. C# has no empty argument slots, so `Export("q3.csv", , 8192)` is CS0839. Since C# 7.2 a named argument may be followed by positional ones only when it sits in its own position: `Export(path: "q3.csv", true)` compiles, `Export(overwrite: true, "q3.csv")` is CS8323. A name the method does not have is CS1739, the same name twice is CS1740, and naming a parameter already filled by position is CS1744. Arguments are evaluated in the order they are written, not in parameter order.

code

csharp · 16 lines
csharp
Exporter.Export("q3.csv");
Exporter.Export("q3.csv", bufferSize: 8192);
Exporter.Export(path: "q3.csv", true);
Exporter.Export(bufferSize: Next("bufferSize", 8192), path: Next("path", "q3.csv"));

static T Next<T>(string label, T value)
{
    Console.WriteLine($"evaluating {label}");
    return value;
}

static class Exporter
{
    public static void Export(string path, bool overwrite = false, int bufferSize = 4096) =>
        Console.WriteLine($"Export({path}, overwrite: {overwrite}, bufferSize: {bufferSize})");
}

go deeper

for a junior

Recall how to skip an optional parameter with a named argument, and that optional parameters must come after required ones.

for a middle

Explain what may serve as a default value, the C# 7.2 rule for named arguments in position, and the written-order evaluation of arguments.

for a senior

Show that you treat public parameter names as part of a library's source contract, and use named arguments to make adjacent bool or int arguments unambiguous in reviews.

for a principal

Be ready to argue when a team's coding standard should require named arguments, such as for boolean flags, and when that adds noise without preventing bugs.

## Optional parameters: what the declaration may say An **optional parameter** is a parameter declared with a default value: `bool overwrite = false`. A caller may leave it out, and the compiler then supplies the default. The **required parameters** are the ones without a default; a call must supply every one of them. Take a reporting library's method: ```csharp public static void Export(string path, bool overwrite = false, int bufferSize = 4096) ``` The compiler enforces a few rules on such a declaration, each with its own diagnostic: - **Optional parameters come last.** `void Log(int level = 1, string text)` is error CS1737, "Optional parameters must appear after all required parameters". A `params` parameter may still follow the optional ones. - **A default must be fixed at compile time.** It can be a constant (`4096`, `"csv"`, an enum member), `null`, `default`, `default(S)` or `new S()` for a value type `S`. `DateTime when = DateTime.Now` and `List<string> names = new List<string>()` are both CS1736, "Default parameter value for 'names' must be a compile-time constant". - **Reference types other than `string` take only `null`.** `object tag = 5` is CS1763: "A default parameter value of a reference type other than string can only be initialized with null". ## Skipping a parameter with a named argument A **named argument** is written `parameterName: value` and binds to a parameter by its name instead of its position. That is the only way to supply a later optional parameter while leaving an earlier one at its default: | Call | Result | |---|---| | `Export("q3.csv")` | `overwrite` false, `bufferSize` 4096 | | `Export("q3.csv", bufferSize: 8192)` | `overwrite` stays false, `bufferSize` 8192 | | `Export("q3.csv", , 8192)` | error CS0839, "Argument missing" | | `Export("q3.csv", size: 8192)` | error CS1739, no parameter named `size` | C# has no empty comma slots. Named arguments work the same way for constructors, indexers and delegate invocations, so a constructor call such as `new ReportWriter(path, bufferSize: 8192)` follows the same rules. Named arguments also work for required parameters, which is often worth doing purely for readability when two adjacent parameters share a type, such as two `bool` flags. ## Mixing named and positional arguments Arguments without names are **positional**: the first fills the first parameter, and so on. The rules for mixing the two forms changed once: 1. Before C# 7.2, every named argument had to come after all positional ones. The C# 7.1 compiler reports CS1738, "Named argument specifications must appear after all fixed arguments have been specified". 2. Since C# 7.2, a named argument may be followed by positional ones **if it sits in its own position**. `Export(path: "q3.csv", true)` compiles: `path` is the first argument and the first parameter, so `true` still binds to `overwrite`. 3. A named argument **out of its position** cannot be followed by a positional one: `Export(overwrite: true, "q3.csv")` is CS8323, "Named argument 'overwrite' is used out-of-position but is followed by an unnamed argument". Two more mistakes have their own errors. Naming a parameter that a positional argument already filled, as in `Export("q3.csv", path: "x.csv")`, is CS1744. Naming the same parameter twice is CS1740. ## The order the arguments run in Named arguments change which parameter receives a value, not when the value is computed. The compiler evaluates arguments **in the order they are written**. In `Export(bufferSize: Next(), path: Name())`, `Next()` runs before `Name()` even though `path` is the first parameter. This matters when argument expressions have side effects such as logging, reading a stream or incrementing a counter. ## Parameter names become part of the contract Once callers write `bufferSize: 8192`, the parameter's name is something they depend on. Renaming `bufferSize` to `size` in the library makes those callers fail with CS1739 the next time they compile. Callers that were already compiled keep working, because a compiled call refers to the method by its parameter types, not by its parameter names. ## What a strong answer covers - Skip optional parameters by naming the next one you pass; never expect a gap to work. - State the placement rule for optional parameters and what may serve as a default. - Know that C# 7.2 relaxed the old rule, and that the remaining restriction is about position. - Know the evaluation order, and that renaming a public parameter is a source-breaking change.

  • Can a C# default parameter value be DateTime.Now or a new List<string>(), and what do you write instead?
    No. A default must be a constant, `null`, `default`, or `new S()`/`default(S)` for a value type, so both are CS1736. Declare `DateTime? when = null` or `List<string>? names = null` and compute the real value inside the method, for example `when ??= DateTime.Now;`, so it is evaluated on each call.
  • In which order are the arguments of Export(bufferSize: Next(), path: Name()) evaluated?
    Left to right as written: `Next()` runs before `Name()`, even though `path` is the first parameter. Naming changes which parameter receives each value, never the order in which the argument expressions run, so side effects happen in the order a reader sees them.
  • Why can renaming a parameter in a library break callers that compiled fine before?
    Callers that pass that argument by name, such as `bufferSize: 8192`, get CS1739 when they recompile against the renamed version. Already-compiled callers keep running, because a compiled call refers to the method by its parameter types, not its names. So a public parameter name is part of the source contract.

  • Leaving an empty slot such as Export("q3.csv", , 8192) skips a parameter.
  • A named argument can never be followed by a positional one.
  • Optional parameters can be declared anywhere in the parameter list.
  • A default can be any expression, such as DateTime.Now, evaluated on each call.
  • Named arguments are evaluated in parameter order, not in written order.
open as a page

In C#, what is a local function, and how does it differ from a private helper method declared on the class?

level: juniorimportance: must knowfreq 55%

basics

~20 s

A local function is a named method declared inside another member. Only that member can call it, it takes no access modifier, it can use the member's locals and parameters, and it can be called before its declaration.

open as a page

In C#, why does a class that declares both `int Parse(string text)` and `long Parse(string text)` fail to compile, and what makes two methods valid overloads?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Overloads must differ in signature: the parameter count and types, a parameter's by-reference kind, or the number of type parameters. Return type, parameter names, default values and params are not part of it, so the second Parse is error CS0111.

open as a page

In C#, how do ref and out parameters differ, and what does the compiler require of the caller and of the called method?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Both pass the caller's variable by reference. A ref argument must be assigned before the call, and the method may read or change it; an out argument may be unassigned, and the method must assign it on every path that returns.

open as a page

In C#, why does `Write(null)` bind to `Write(string?)` when `Write(object?)` also exists, yet fail with CS0121 once `Write(Exception?)` is declared?

level: middleimportance: must knowfreq 55%

basics

~20 s

A null literal converts to every reference type, so the more specific parameter wins: string converts to object but not back. string and Exception do not convert to each other, so no overload is best and the call is error CS0121.

open as a page

In C#, a method meant to replace the caller's List<string> assigns a new list to its parameter, but the caller keeps the old list; why?

level: middleimportance: must knowfreq 70%

basics

~20 s

A List<string> parameter holds a copy of the caller's reference. Calling Add through it changes the shared list, but assigning a new list rebinds only the method's copy. Declare the parameter ref, or return the new list.

open as a page

A C# reporting library's v2 changes `Export`'s default `bufferSize` from 4096 to 81920; why does an app compiled against v1 still pass 4096 after the DLL is upgraded?

level: seniorimportance: must knowfreq 48%

basics

~20 s

The C# compiler copies an optional parameter's default into each call site when the caller is compiled, so the app's IL still contains the literal 4096. Only rebuilding the app against v2 picks up 81920.

open as a page

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%

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.

open as a page

Since C# 13, what does the compiler build for calls to `params ReadOnlySpan<int>`, `params IEnumerable<int>` and `params List<int>` parameters, and what does each cost?

level: middleimportance: should knowfreq 35%

basics

~20 s

Since C# 13, params ReadOnlySpan<int> gets a span over a buffer on the caller's stack, so no heap allocation; params IEnumerable<int> gets a compiler-generated read-only collection; params List<int> gets a new List<int> filled with Add.

open as a page

In C#, why does a recursive lambda assigned to a Func or Action variable fail with CS0165, while a recursive local function compiles?

level: middleimportance: should knowfreq 48%

basics

~20 s

The lambda's body reads the delegate variable inside that variable's own initializer, before it is definitely assigned, so the compiler reports CS0165. A local function is a named method in scope across its block, so it can call itself directly.

open as a page

In C#, a logger declares `Log(string message)`, `Log(string message, int level = 0)` and `Log(string format, params object[] args)`; which one does `Log("ready")` call, and why?

level: middleimportance: should knowfreq 38%

basics

~20 s

Log(string message) is called. All three accept the string equally well, so tie-breakers decide: a method usable without params expansion beats the params one, and one that needs no default value filled in beats Log(string, int = 0).

open as a page

Why does C# reject async Task<bool> TryLoadAsync(string path, out string text) with CS1988, and how do you return both results instead?

level: middleimportance: should knowfreq 45%

basics

~20 s

An async method hands its Task back at the first pending await and finishes later, so it cannot keep a reference to the caller's variable. Return Task<(bool Ok, string Text)>, a result record or a nullable value instead.

open as a page

Why does C# reject Interlocked.Increment(ref stats.Hits) with CS0206 when Hits is an auto-property, and what may a ref argument be?

level: middleimportance: should knowfreq 42%

basics

~20 s

A ref or out argument must be a variable: a local, a parameter, a field or an array element. A property or a List<T> indexer is a method call that returns a value, so the compiler reports CS0206.

open as a page

In C#, `IExporter` declares `Export(string path, bool overwrite = false)` and `CsvExporter` implements it with `overwrite = true`; why does `Export("q3.csv")` depend on the variable's type?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The compiler copies a default into the call from the declaration it binds to, which depends on the variable's static type: IExporter says false, CsvExporter says true. At run time CsvExporter's body runs either way, with whichever value the call passed.

open as a page

In a C# hot path, when does a local function that captures locals allocate nothing, and what makes it heap-allocate like a lambda?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Called directly, never converted to a delegate, and sharing no captures with a lambda, it keeps captures in a struct passed by reference: no allocation. A delegate conversion, a sharing lambda, or an async or iterator local function forces a heap closure class.

open as a page

A C# paging iterator checks pageSize but throws ArgumentOutOfRangeException only when the caller first enumerates; why, and how does a local function make it throw at the call?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Any yield makes the whole method an iterator, so its checks run only on the first MoveNext. Keep the checks in a public method with no yield and return a local iterator function, so bad arguments throw at the call.

open as a page

In a C# code review, why mark a local function static, and what does the compiler then reject and still allow inside it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A static local function (C# 8) cannot capture: referencing an enclosing local or parameter raises CS8421, and this, base or an instance member raises CS8422. Constants, static members and nameof still work, so it never builds a closure.

open as a page

In C#, a logging facade has `Log(object)`, `Log(string)`, `Log<T>(T)` and `Log(ReadOnlySpan<char>)`; why does `Log(42)` reach the generic overload, and a `char[]` miss the span one?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Log<T>(T) infers T from the argument, so its parameter is an identity match, which beats boxing 42 to object and converting a char[] to ReadOnlySpan<char>. Non-generic overloads win only ties, which is why strings still reach Log(string).

open as a page

In C#, why does a `short` argument bind to `Write(int)` over `Write(long)` and `Write(object)`, and why can a literal `0` pick an enum overload over `Write(object)`?

level: seniorimportance: should knowfreq 45%

basics

~20 s

C# ranks the parameter types: int converts implicitly to long but not back, so int is the better target, and boxing to object loses to both. A literal 0 converts implicitly to any enum, which converts to object, so the enum overload wins.

open as a page

A hot C# method takes a large readonly struct Matrix; what changes when its parameter is declared in versus ref readonly?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Both pass a read-only reference instead of copying the struct. An in parameter accepts any expression and quietly copies non-variables into a temporary; a ref readonly parameter expects a variable passed with in or ref and warns otherwise.

open as a page

For a public C# library on NuGet, should `Export` grow through optional parameters or overloads, and how do you add a parameter in v2 without breaking compiled callers?

level: principalimportance: should knowfreq 30%

basics

~20 s

Appending an optional parameter keeps source compatibility but removes the old signature, so compiled callers hit MissingMethodException. Keep the v1 signature as an overload without defaults that forwards to the new method, and put defaults on one longest overload only.

open as a page

In C#, why does `fileSink.Write("disk full")` reach the derived class's `Write(object)` over an inherited `Write(string)`, and why can't `[OverloadResolutionPriority]` on the base change that?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

If a method declared in the derived class is applicable, every candidate declared in a base class is removed, and an override counts as declared in the base. OverloadResolutionPriority (C# 13) only ranks applicable overloads within one declaring type, after that removal.

open as a page