skip to content

Since C# 10, var floor = Pricing.ApplyFloor; compiles for a single-overload method; what delegate type is inferred, and when does inference fail?

level: seniorimportance: should knowfreq 35%

answer

  1. natural type, C# 10
  2. Func or Action first
  3. synthesized type otherwise
  4. overloads need one signature
  5. CS8917

basics

~20 s

C# 10 gives a lambda or method group a natural type: Func<...> when it returns a value, Action<...> when void, or a synthesized type when neither fits the signature. It fails with CS8917 when overloads share no signature or lambda parameters are untyped.

solid answer

~40 s

Since C# 10 a lambda or method group can have a **natural type**, so `var floor = Pricing.ApplyFloor;` infers `Func<decimal, decimal>`. The rule: if every parameter and the return are by value, there are at most 16 parameters and all are valid type arguments, the type is `Func<...>` (or `Action<...>` for `void`); otherwise, for example with an `out` parameter or a lambda default value, the compiler synthesizes an internal anonymous delegate type. A method group has a natural type only when its candidates share one signature, so `var log = Console.WriteLine;` fails with CS8917, "The delegate type could not be inferred." A lambda needs explicit parameter types (`(decimal price) => ...`) for the same reason. The inferred type is never `Predicate<T>` or a custom delegate; target-type the variable when an API needs one.

code

csharp · 19 lines
csharp
using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

var seasonal = (decimal price) => price * 0.90m;   // natural type Func<decimal, decimal>
var floor = Pricing.ApplyFloor;                     // one candidate: Func<decimal, decimal>
var round = (decimal price, int digits = 2) => Math.Round(price, digits);   // default value: synthesized type
// var log = Console.WriteLine;                     // CS8917: many overloads, no common signature
// var half = price => price / 2;                   // CS8917: parameter type unknown

Console.WriteLine(floor(seasonal(15m)));
Console.WriteLine(round(19.987m));
Console.WriteLine(floor.GetType().Name + " / " + round.GetType().Name);

static class Pricing
{
    public static decimal ApplyFloor(decimal price) => Math.Max(price, 20m);
}

go deeper

for a junior

Recall that since C# 10 var can hold a typed lambda or a single-overload method group, and the type is usually a Func or an Action.

for a middle

Explain the Func, Action or synthesized-type rule and why an overloaded method group or untyped lambda parameters produce CS8917.

for a senior

Use natural types deliberately: target-type variables when an API needs a specific delegate, and watch for CS8974 when a method name loses its parentheses.

for a principal

Decide whether a team prefers explicit delegate types over var for lambdas in public-facing code, weighing readability against the noise of long Func signatures.

## What a natural type is Before C# 10, a **lambda expression** or a **method group** (a method name without the call parentheses, such as `Pricing.ApplyFloor`) had no type of its own. It could only be converted to a delegate type the context supplied, so `var f = Pricing.ApplyFloor;` was an error and `object o = random.NextDouble;` failed with CS0428. C# 10 introduced the **natural type**: when the compiler can determine one signature, it picks a delegate type for you. This made `var` declarations and APIs that take a `Delegate` parameter work without casts. ## How the compiler picks the type For a signature with parameter types `P1 ... Pn` and return type `R`, the lambda-improvements proposal for C# 10 defines: 1. If any parameter or the return is **not by value** (`ref`, `out`, `in`), there are **more than 16 parameters**, or a type is not a valid type argument, the compiler **synthesizes an internal anonymous delegate type** with the exact signature. 2. Otherwise, if `R` is `void`, the type is `System.Action<P1, ..., Pn>`. 3. Otherwise it is `System.Func<P1, ..., Pn, R>`. A lambda with a **default parameter value** (C# 12) or a `params` parameter also gets a synthesized type, because `Func` cannot carry that metadata; running `var round = (decimal price, int digits = 2) => ...` and printing its type shows `<>f__AnonymousDelegate0`3`. | Expression | Inferred type | |---|---| | `(decimal price) => price * 0.90m` | `Func<decimal, decimal>` | | `Pricing.ApplyFloor` (one overload) | `Func<decimal, decimal>` | | `(decimal price) => price > 0m` | `Func<decimal, bool>`, never `Predicate<decimal>` | | `(decimal p, int digits = 2) => ...` | synthesized anonymous delegate type | | `Console.WriteLine` (many overloads) | none: CS8917 | | `price => price / 2` | none: CS8917 | ## When inference fails - **Overloaded method groups.** A method group has a natural type only if all candidate methods share a common signature. `Console.WriteLine` has many overloads, so `var log = Console.WriteLine;` reports **CS8917**, "The delegate type could not be inferred." Adding a target type (`Action<string> log = Console.WriteLine;`) picks the overload. - **Untyped lambda parameters.** `var half = price => price / 2;` has nothing to infer `price` from, so it also reports CS8917. Write `(decimal price) => price / 2`. - **A specific delegate type is required.** The natural type is always `Func`, `Action` or a synthesized type, never `Predicate<T>`, `EventHandler` or your own `DiscountRule`. Declare the variable with the type the API expects instead of `var`. ## Target type still wins A natural type is used only when the context does not supply a delegate type. Whenever there is a target type, the ordinary conversion applies: - `Predicate<decimal> isSellable = price => price > 0m;` gives a `Predicate<decimal>`, because the declared type is the target. - Passing a lambda to a parameter typed `Func<decimal, decimal>` or to an `Expression<Func<decimal, bool>>` parameter converts it to that type, natural type or not. - A parameter typed `Delegate` or `MulticastDelegate`, or a variable typed `object`, is where the natural type is realized: `Delegate d = (decimal p) => p * 2m;` creates a `Func<decimal, decimal>`, while `MulticastDelegate m = Math.Max;` fails with CS8917 because `Math.Max` has many overloads. ## Side effects of the feature worth knowing - Converting a method group to `object` now compiles with warning **CS8974** ("Converting method group ... to non-delegate type 'object'. Did you intend to invoke the method?"), because forgetting the parentheses is usually a bug. - Overload resolution was adjusted to prefer candidates whose conversions do not depend on an inferred natural type, so most existing calls keep the binding they had before C# 10. - Allocation: the compiler caches the delegate for a lambda that captures nothing, and since C# 11 it also caches the delegate for a method group bound to a **static** method, so repeated conversions of `Pricing.ApplyFloor` in a loop no longer allocate each time. A capturing lambda or a method group bound to an instance method still creates a delegate per evaluation. ## In an interview Say what the natural type is, give the Func/Action/synthesized rule, name CS8917 and its two common causes, and point out that `var` never gives you `Predicate<T>` or a custom type.

  • Does converting the same method group to a delegate in a loop allocate every time?
    For a method group bound to a static method, no: since C# 11 the compiler caches the delegate and reuses it, so two conversions of `Pricing.ApplyFloor` return the same instance. A method group bound to an instance method still creates a delegate per conversion, because the target object is part of the delegate.
  • Why does object o = random.NextDouble; compile today with only a warning?
    With natural types the method group converts to `System.Object` by being realized as a `Func<double>` instance, so the conversion is legal. Because writing a method name without parentheses is usually a mistake, the compiler reports warning CS8974 asking whether you meant to invoke it. Before C# 10 the same line was error CS0428.

  • var floor = Pricing.ApplyFloor; infers a Predicate or custom delegate if one matches
  • Method groups gained a natural type only in C# 12
  • var log = Console.WriteLine; compiles and picks the first overload
  • A lambda with untyped parameters gets dynamic as its parameter type under var
  • A lambda with a default parameter value still gets a plain Func as its natural type