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?
answer
- candidates grouped by declaring type
- base methods removed when derived applies
- an override belongs to its base
- priority is compared within one type
basics
~20 sIf 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.
solid answer
~50 sOverload resolution removes every candidate declared in a base class when an applicable candidate is declared in a more derived class. `FileSink.Write(object)` accepts a string, so the inherited `Write(string)` is removed before conversions are compared, even though the string match is better. An `override` does not help: it counts as declared where the virtual method was first declared, in the base. Casting to the base type, `((Sink)fileSink).Write("disk full")`, binds to `Write(string)`, and virtual dispatch then runs the override. C# 13 added `OverloadResolutionPriorityAttribute`: within each declaring type, applicable candidates with a lower priority than the highest are removed. Because grouping is per type, a base class cannot raise its overload above a derived one. The attribute is rejected on an `override` (CS9261), its priority is taken from the original declaration, and a caller compiled with `LangVersion` 12 or lower ignores it.
code
csharp · 13 linesvar sink = new FileSink();
sink.Write("disk full"); // FileSink.Write(object)
((Sink)sink).Write("disk full"); // the override of Write(string), by virtual dispatch
class Sink
{
public virtual void Write(string message) => Console.WriteLine("Sink.Write(string)");
}
class FileSink : Sink
{
public override void Write(string message) => Console.WriteLine("FileSink.Write(string) override");
public void Write(object value) => Console.WriteLine("FileSink.Write(object)");
}go deeper
Recall that methods declared in a derived class are considered before inherited ones, so an inherited exact match can be skipped.
Explain the derived-first removal step and why an override still counts as declared in the base class.
Diagnose a call that skips an inherited overload, fix it with a cast or a rename, and know what OverloadResolutionPriority can and cannot change.
Decide when a library should use OverloadResolutionPriority to steer callers, accepting that deprioritized overloads become hard to reach and older callers ignore it.
## The derived class's candidates go first A logging library has a `Sink` base class with `public virtual void Write(string message)`. A `FileSink` subclass overrides it and adds a convenience overload, `public void Write(object value)`. A caller writes: ```csharp var sink = new FileSink(); sink.Write("disk full"); // FileSink.Write(object) ``` The string-typed `Write(string)` would be an identity match, yet the call binds to `Write(object)`. The reason is a step that runs **before** the conversions are compared: 1. Member lookup collects every `Write` visible on `FileSink`, including inherited ones. 2. The applicable candidates are kept. 3. For each candidate declared in some type `C`, **every candidate declared in a base type of `C` is removed**. 4. Only then are the remaining candidates ranked by their conversions. `FileSink.Write(object)` is applicable to a string, so step 3 removes everything declared in `Sink`. The compiler never compares string against object. ## Why the override does not count Overriding `Write(string)` in `FileSink` does not make it a `FileSink` candidate. For overload resolution an override counts as the method **first declared** in the base class: resolution picks a virtual slot, and which body fills the slot is a run-time question. So: - `sink.Write("disk full")` binds to `FileSink.Write(object)`. - `((Sink)sink).Write("disk full")` has only `Sink`'s members to look at, binds to `Sink.Write(string)`, and **virtual dispatch** then runs the `FileSink` override. - A caller that wants the string overload through a `FileSink` variable casts the receiver, or the class renames the convenience method. How virtual dispatch chooses the override at run time is covered in the lesson on overriding and hiding. ## OverloadResolutionPriority (C# 13) C# 13 introduced `System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute`, which ships in the .NET 9 and later libraries. It assigns an `int` **priority** to a method, constructor or indexer; members without it have priority 0. After the applicable candidates are found, the compiler: 1. **groups** them by declaring type; 2. within each group, **removes** every candidate whose priority is lower than the highest in that group; 3. recombines the groups and continues with the usual ranking. Inside one type, this lets an author steer a call that would otherwise bind elsewhere. With `[OverloadResolutionPriority(1)]` on `Log(ReadOnlySpan<char>)`, `Log("ready")` binds to the span overload even though `Log(string)` is an identity match, because `Log(string)` is removed first. `Log(42)` is unaffected: the span overload is not applicable to an `int`, and priorities only compare applicable candidates. ## Why the base cannot win The priority pass runs on the set that the derived-first rule has already reduced. An `AppLogger` subclass that declares `Log(object? value, int level = 0)` takes `Log("ready")` away from every `Logger` overload, including one with priority 1, because the base candidates are gone before priorities are compared. The csharplang proposal calls this intentional: it prevents a base type from always outranking a derived type. ## Rules the compiler enforces | Situation | What the C# 14 compiler does | |---|---| | Attribute on an `override` | error CS9261; the priority comes from the original declaration | | Attribute on a non-indexer property | error CS9262 | | Attribute applied with `LangVersion` 12 | error CS9202: the feature needs C# 13 | | A caller compiled with `LangVersion` 12 or lower | priorities are ignored, the old rules apply | | A caller compiled before the attribute was added | keeps its old binding until it is recompiled | The attribute is also rejected on accessors, conversion operators, lambdas, local functions, finalizers and static constructors. ## When to reach for which tool When a call skips an inherited overload, work through it in this order: 1. Check the receiver's **static type**: the declared type of the variable decides which classes' methods are candidates, not the object it holds at run time. 2. Look for any applicable method declared in a **more derived** class, including convenience overloads with `object`, `params` or optional parameters, which accept almost any argument. 3. Remember that an `override` does not count as a derived-class declaration. 4. Only then compare conversions and priorities among what is left. Then pick the fix: - Make a derived class's convenience overload unambiguous by giving it a distinct name, not by fighting the derived-first rule. - Use priority within one type to retire an overload without deleting it, or to send new callers to a cheaper overload, and accept that the lower-priority overload becomes hard to reach from source. - Expect priority changes to reach callers only when they recompile.
- What happens if a derived class puts `[OverloadResolutionPriority(2)]` on its `override` of a virtual method?The compiler rejects it with error CS9261, "Cannot use 'OverloadResolutionPriorityAttribute' on an overriding member." The priority of an overridden method is always read from its least-derived declaration, so only the base declaration can carry the attribute.
- A library adds `[OverloadResolutionPriority(1)]` to a new overload. When do callers start binding to it?Only when they are recompiled, and only with C# 13 or later. Overload resolution is a compile-time decision stored in the caller's IL, so existing binaries keep calling the old overload. A project that pins `LangVersion` to 12 or lower ignores the priority and keeps the old rules even after rebuilding.
- The compiler always picks the overload with the best parameter match, wherever it is declared.
- Overriding Write(string) in the derived class makes it a derived-class candidate.
- A high OverloadResolutionPriority on a base method beats any derived overload.
- OverloadResolutionPriority is applied at run time when the method is called.
- An override can raise its own priority with the attribute.
Assumes C# 14 on .NET 10; OverloadResolutionPriorityAttribute is a C# 13 feature, and the attribute type ships in the .NET 9 and later libraries.