skip to content

In C#, why do `Save<T>(T item) where T : struct` and `Save<T>(T item) where T : class` in one class fail with CS0111?

level: seniorimportance: should knowfreq 32%

answer

  1. what makes a method signature
  2. constraints and return type left out
  3. separate classes, separate members
  4. candidates dropped when constraints fail

basics

~20 s

Constraints are not part of a C# method signature, so both declare Save<T>(T) and the second is CS0111. Use different names, or put each in its own static class as an extension method; overload resolution discards a candidate whose constraint fails.

solid answer

~50 s

A C# method signature for overloading is the name, the number of type parameters, and the parameter types and modifiers. Constraints and the return type are not in it, so two `Save<T>(T item)` methods that differ only in `where` clauses are duplicates: CS0111. The fixes that work are different names (`SaveValue`, `SaveReference`) or moving each method to its own static class as an extension method. Then they are different members, and since C# 7.3 overload resolution drops any generic candidate whose inferred type arguments break its constraints, so `row.Describe()` picks the `struct` one and `"x".Describe()` the `class` one. Changing the struct overload to `Save<T>(T? item)` is a legal overload but does not help `Save(42)`: `T` cannot be inferred from `int` into `Nullable<T>` (CS0411 on its own), so only the class overload is left and the call fails with CS0452.

code

csharp · 19 lines
csharp
Console.WriteLine(new Row(7).Describe());
Console.WriteLine("ticket-17".Describe());
Console.WriteLine(Format.Show(3));
Console.WriteLine(Format.Show("x"));

static class ValueDescribers
{
    public static string Describe<T>(this T value) where T : struct => $"value: {value}";
}
static class ReferenceDescribers
{
    public static string Describe<T>(this T value) where T : class => $"reference: {value}";
}
static class Format
{
    public static string Show<T>(T value) where T : struct => $"generic {value}";
    public static string Show(object value) => $"object {value}";
}
readonly record struct Row(int Id);

go deeper

for a junior

Recall that overloads must differ in parameter types or type-parameter count, and that a where clause does not count.

for a middle

Explain the signature rule and the CS0111 it produces, and name the fix that always works: give the two methods different names.

for a senior

Show why the extension-method split works: separate members plus the C# 7.3 rule that drops candidates whose constraints fail. Know that a T? overload is not reached by Save(42).

for a principal

Prefer explicit names over constraint-driven dispatch in shared APIs; reserve the extension-method split for fluent call sites where one name truly reads better.

## What counts as a signature Two methods in one type may share a name only if their **signatures** differ. In C# the signature used for this check is: - the method name; - the number of type parameters (`Save<T>` and `Save<T, U>` are different); - the type and kind (`ref`, `out`, `in`, value) of each parameter, in order. Two things are deliberately **not** in it: the **return type** and the **type-parameter constraints**. So these two declarations are the same signature, `Save<T>(T)`: ```csharp public static void Save<T>(T item) where T : struct { } public static void Save<T>(T item) where T : class { } // CS0111 ``` The SDK reports **CS0111**: "Type 'Store' already defines a member called 'Save' with the same parameter types". The same error appears for `int R<T>(T x)` beside `void R<T>(T x)`. ## Fixes that work | Approach | Result | |---|---| | Different names: `SaveValue<T>` / `SaveReference<T>` | always works; the call site states the intent | | Extension methods in two static classes | works: each is a separate member, and resolution discards the one whose constraint fails | | Different parameter types, e.g. `Save<T>(T? item) where T : struct` | a legal overload, but `Save(42)` cannot infer `T` into `Nullable<T>` (CS0411 when it is the only candidate), so it only helps callers passing `int?` | | Different arity: add a second type parameter | compiles, but forces callers to supply a meaningless type argument | ## Why the extension-method split works Each extension method lives in its own static class, so the two are different members and no CS0111 arises: ```csharp static class ValueDescribers { public static string Describe<T>(this T value) where T : struct => $"value: {value}"; } static class ReferenceDescribers { public static string Describe<T>(this T value) where T : class => $"reference: {value}"; } ``` At the call `new Row(7).Describe()`, both are candidates. Type inference gives `T = Row` for both, and the `class` candidate's constraint fails. Since **C# 7.3**, overload resolution removes such candidates from the set (the "improved overload candidates" change) instead of picking one and then reporting the constraint error. Only the `struct` method is left, so it is called; for `"ticket-17".Describe()` the reverse happens. The same rule explains a pair that surprises people: ```csharp public static string Show<T>(T value) where T : struct => $"generic {value}"; public static string Show(object value) => $"object {value}"; ``` `Show(3)` calls the generic method, a better match than converting to `object`. `Show("x")` would also prefer the generic method (an identity conversion to `string`), but its constraint fails, so it is discarded and `Show(object)` is called. No error is reported. ## Traps when the pruning cannot help 1. **One class, two constrained overloads**: CS0111 at the declaration, before any call site is considered. 2. **All candidates fail**: when only the constrained generic is left and the type argument breaks it, the call reports the constraint error itself. With `Save<T>(T) where T : class` and `Save<T>(T?) where T : struct`, `Save(42)` reports CS0452 against the class overload, because the `Nullable<T>` one dropped out at type inference. 3. **Static-method form**: `ValueDescribers.Describe(row)` names one class, so pruning has nothing to choose between and a failing constraint is reported as an error. 4. **Generic resolution belongs to call-site rules**: which of several valid overloads wins (exact match, better conversion, generic vs non-generic tie-breaks) is overload resolution in general, covered with method overloads; the constraint-specific part is only the pruning step. ## In code review - Two methods with the same name, parameter list and different `where` clauses in one type: CS0111, rename them. - A "pick by constraint" API is cleanest as differently named methods; reserve the extension-method split for fluent APIs whose call sites read better with one name. - Do not rely on a `T?` overload to catch plain value-type arguments; inference will not reach it. - When a caller reports that adding a `using` directive changed which method runs, check for extension methods split by constraints: bringing a new static class into scope adds candidates to the same pruning step.

  • In C#, why doesn't changing the struct overload to `Save<T>(T? item) where T : struct` make `Save(42)` reach it?
    `Save<T>(T?)` takes `Nullable<T>`, so it is a different signature and compiles beside `Save<T>(T)`. But type inference cannot infer `T` from an `int` argument into `Nullable<T>`; on its own that call is CS0411. The candidate drops out, the class overload is the only one left, and `Save(42)` fails with CS0452. It works only for callers that pass an `int?`.
  • With C# `Show<T>(T value) where T : struct` and `Show(object value)` in one class, why does `Show("x")` compile?
    Inference gives `T = string` for the generic method, which would beat the conversion to `object`, but `string` fails the `struct` constraint. Since C# 7.3, overload resolution removes candidates whose type arguments break their constraints before choosing, so only `Show(object)` remains and is called. `Show(3)` keeps both and picks the generic method.
  • Is the return type part of a C# method signature for overloading?
    No. `int R<T>(T x)` and `void R<T>(T x)` in one type are CS0111, just like methods differing only in constraints. The overloading signature is the name, the type-parameter count and the parameter types and modifiers.

  • Constraints are part of the signature, so methods differing only in where clauses are valid overloads.
  • The runtime picks the overload whose constraint matches the actual type argument.
  • Changing only the return type is enough to make two generic overloads distinct.
  • Adding a T? parameter to the struct overload makes Save(42) bind to it.
  • Two extension methods with the same shape in different static classes always give CS0121.