C# 15 union types: Why Lambdas and Delegates Need a Target

C# 15 union types: Why Lambdas and Delegates Need a Target C# 15 union types: Why Lambdas and Delegates Need a Target

A union that accepts either text or a callback sounds straightforward—until the callback is written as a lambda and the compiler rejects it. This surprising edge of C# 15 union types comes from a fundamental distinction: a lambda expression is not automatically a value of a particular delegate type. The compiler must first obtain a target delegate signature, and a union assignment does not always provide that target in the way a normal delegate assignment does.

The practical rule is simple: a value whose compile-time type is an eligible union case can participate in the union conversion, but an untyped lambda may need to become a concrete delegate first. Delegate instances can also fail when their static type does not match or convert to a valid case. Understanding case selection, target typing, and conversion sequencing makes these errors predictable.

A simple C# 15 union type

Consider a union whose cases are int and string. Using the C# 15 union declaration form, a minimal example is:

public union NumberOrText(int Number, string Text);

NumberOrText first = 42;
NumberOrText second = "forty-two";

Both assignments have a typed source expression. The integer literal has type int, while the string literal has type string. The compiler can identify one valid union case and apply the union conversion.

Union member definitions matter. The set of declared case types determines which source values are eligible, and a conversion must lead to an unambiguous case. A union is not simply an object container that accepts every value and records its runtime type.

Projects reproducing these examples should target the .NET 11 SDK and select C# 15 explicitly when the project does not already use it:

<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
  <LangVersion>15.0</LangVersion>
</PropertyGroup>

Union syntax and conversion details should always be checked against the installed compiler and the current C# 15 union proposal. Preview SDKs and older proposal drafts may produce different diagnostics or support different portions of the feature.

Lambda expressions are not delegate instances

Four concepts must be kept separate:

  • Lambda expression: Source syntax such as () => 42. Its parameter and return requirements are checked against a target function type.
  • Delegate type: A named or generic type such as Func<int>, Action<string>, or a custom delegate declaration.
  • Delegate instance: An object whose compile-time type is a delegate type and which references callable code.
  • Union case: One of the types explicitly admitted by a union declaration.

This distinction becomes visible with a callable case:

public union NameOrFactory(string Name, Func<int> Factory);

NameOrFactory name = "next-id";
NameOrFactory factory = () => 42; // Compiler error

The first assignment starts with a string, so case selection is direct. In the second assignment, the lambda needs Func<int> as its target type before it can become a delegate. The union is the immediate assignment target, however, and the union conversion does not necessarily target-type an anonymous function through each possible case.

This is why reasoning that “the union contains Func<int>, so the lambda must be a Func<int>” is unsafe. C# conversion rules do not generally search through arbitrary conversion chains merely because one chain would appear intuitive.

Why target typing changes the result

A conventional delegate assignment provides an immediate target:

Func<int> getNumber = () => 42;

The compiler knows that the lambda must take no arguments and return an int. It can validate the body and create the delegate conversion. A direct union assignment introduces two conceptual steps:

  1. Convert the lambda to Func<int>.
  2. Convert the resulting Func<int> value to NameOrFactory.

C# implicit conversions are not freely composable. The existence of each conversion in isolation does not guarantee that the compiler may chain them in a single assignment. Union case selection also needs a well-defined source, while an anonymous function may depend on the selected case to acquire its type. That circular dependency is the heart of the failure.

Modern C# can infer a natural delegate type for many lambdas in contexts such as var, but natural-type inference does not turn every anonymous function into an independently typed expression. Overloaded method groups, inferred parameters, ref modifiers, optional expression-tree targets, and multiple compatible delegate signatures can still require explicit context.

The reliable fix: create the intended delegate first

Give the lambda a concrete delegate target, then assign the typed value to the union:

Func<int> getNumber = () => 42;
NameOrFactory factory = getNumber;

An explicit delegate construction is equally clear:

NameOrFactory factory = new Func<int>(() => 42);

An explicit cast can be useful when the intermediate variable adds noise:

NameOrFactory factory = (Func<int>)(() => 42);

In each version, lambda conversion happens in a context whose target is unambiguously Func<int>. The subsequent union conversion sees a typed delegate instance and a matching case.

Why an existing delegate can still fail

Having a delegate object at runtime is not enough. C# union type conversion is based on the expression’s compile-time type and the declared union cases.

Func<int> typed = () => 42;
Delegate erased = typed;

NameOrFactory good = typed;
NameOrFactory bad = erased; // No valid implicit case conversion

The runtime object referenced by erased is still a Func<int>, but the expression’s static type is Delegate. Because Delegate is not a case of NameOrFactory, the compiler does not inspect the runtime object and choose a narrower case.

A checked cast can restore the required static type when appropriate:

NameOrFactory restored = (Func<int>)erased;

Delegate variance creates similar traps. For example, Func<string> can convert to Func<object> because its result is covariant, but the reverse is not valid. If the union case is Func<string>, a variable declared as Func<object> cannot enter that case merely because its current implementation happens to return a string.

Overload resolution and multiple callable cases

A union containing several delegate types makes target typing even less obvious:

public union Callback(
    Func<int> NumberFactory,
    Func<string> TextFactory);

Callback callback = () => 42; // Do not rely on case probing

The lambda’s body may suggest one delegate, but union conversion is not a general overload-resolution mechanism for anonymous functions. State the intended case:

Callback callback = (Func<int>)(() => 42);

Method overloads introduce another layer:

static void Queue(Func<int> callback) { }
static void Queue(NameOrFactory item) { }

Queue(() => 42);

The direct Func<int> overload supplies a delegate target and is the applicable path. If only the union overload exists, the lambda may be rejected because the argument lacks the target conversion needed to enter the callable case. Adding more union cases can also turn a previously unique conversion into an ambiguous one, so case-set changes deserve the same review as overload-set changes.

Practical design alternatives

Use explicit delegates at the boundary

When an API accepts a union with callable cases, document the delegate signature and convert lambdas before the call. A helper method can centralize that intent:

static NameOrFactory FromFactory(Func<int> factory) => factory;

NameOrFactory item = FromFactory(() => 42);

Wrap callable behavior in a nominal type

If callbacks carry business meaning, a record or class often creates a better union case:

public sealed record NumberFactory(Func<int> Invoke);
public union NameOrFactory(string Name, NumberFactory Factory);

NameOrFactory item = new NumberFactory(() => 42);

The wrapper provides a place for validation, cancellation policy, metadata, or additional behavior. It also prevents several structurally similar delegates from becoming confusing cases.

Prefer methods or factories for public APIs

A supported construction method with a delegate parameter gives the lambda an ordinary target-typed argument context. This can be more discoverable than asking callers to remember a cast, especially when a union contains multiple function types.

How unions compare with older C# patterns

  • object: Accepts a delegate instance after lambda conversion but loses the closed set of cases. A lambda still normally requires a target type; object value = () => 42 does not magically define a delegate signature.
  • Interfaces: Provide polymorphic behavior and extensibility. Lambdas convert directly only when an applicable interface conversion exists, such as a supported function-interface scenario; ordinary interfaces are not delegate targets.
  • Abstract base classes: Model related nominal types and shared implementation, but delegates cannot inherit from an application-defined base class.
  • Traditional discriminated unions: A sealed hierarchy of records gives every case a named wrapper. It requires more code but naturally solves lambda targeting when a wrapper constructor accepts a specific delegate.
  • C# union types: Express a closed choice between case types with compiler-defined conversion and matching behavior. They remain governed by the C# type system rather than runtime guesswork.

Common compiler errors and troubleshooting

Depending on the exact expression and compiler build, developers may see messages equivalent to “cannot convert lambda expression to type” or “cannot implicitly convert type.” Diagnostic identifiers can differ as the compiler identifies the failure at either lambda conversion or union conversion.

  1. Confirm that the intended delegate type is actually declared as a union case.
  2. Assign the lambda to that delegate type outside the union assignment.
  3. Check the delegate’s parameter modifiers, return type, nullability, and variance.
  4. Inspect the variable’s compile-time type rather than its runtime type.
  5. Look for multiple cases reachable from the same source type.
  6. Reduce overloads and method groups to one explicit delegate cast.
  7. Verify the SDK and language version against the official What’s new in C# documentation.

Frequently asked questions

Can a lambda be a C# union case?

A lambda expression is syntax, not a case type. A compatible delegate type such as Func<int> can be a union case. Convert the lambda to that delegate type before applying the union conversion when direct assignment lacks target typing.

Why does assigning a delegate variable work when the same lambda fails?

The variable already has a concrete delegate type. The compiler can compare that static type with the union’s case definitions. The raw lambda still needs a target signature, and the union context may not provide one.

Will casting to Delegate fix the error?

Usually not. Delegate erases the specific signature and will only help if Delegate itself is a valid union case. Cast or assign to the exact intended delegate type instead.

Should callable unions use Func and Action cases?

They can, but explicit wrapper records or factory methods are often clearer for public APIs. Wrappers distinguish semantic roles, improve diagnostics, and avoid ambiguity when several callbacks have similar signatures.

Are union conversions based on runtime types?

No. The compiler analyzes declared case types, the expression’s compile-time type, applicable implicit conversions, and ambiguity. It does not inspect the future runtime value to select a case.

The key takeaway

C# 15 union types do not make lambda and delegate conversions interchangeable. An ordinary typed value gives the compiler a source type from which it can select a valid union case. A lambda often needs the selected delegate case to establish its type in the first place, and C# does not automatically chain those conversions in every union context. When callable values are required, create the exact delegate explicitly, use a construction helper, or wrap the callback in a meaningful nominal type. Those patterns make intent visible and keep union conversion predictable.

Leave a Reply

Your email address will not be published. Required fields are marked *