Resolving Overload Ambiguity with Collection Expressions

 
 
  • Gérald Barré

OverloadResolutionPriority allows you to specify which method overload the compiler should prefer when multiple overloads are applicable. This is useful when methods accept types that can be implicitly converted to each other and you need to control which overload gets selected.

This feature is especially helpful when working with existing overloads that accept collections. When using collection expressions (like ["a", "b"]), the compiler may find multiple applicable overloads and report an ambiguity error. The OverloadResolutionPriority attribute lets you guide the compiler to the intended overload. Here's an example:

C#
Foo.Bar(["a"]); // ❌ Ambiguous call between Bar(List<string>) and Bar(ReadOnlySpan<string>)

class Foo
{
    public static void Bar(ReadOnlySpan<string> values) { }
    public static void Bar(List<string> values) { }
}
C#
Foo.Bar(["a"]); // ✔️ calls Bar(ReadOnlySpan<string>)

class Foo
{
    [OverloadResolutionPriority(1)]
    public static void Bar(ReadOnlySpan<string> values) { }
    public static void Bar(List<string> values) { }
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?