Resolving Overload Ambiguity with Collection Expressions

 
 
  • Gérald Barré

OverloadResolutionPriority allows you to specify which method overload should be preferred by the compiler when multiple overloads are applicable. This can be useful in scenarios where you have multiple methods with types that can be implicitly converted to each other, and you want to control which overload is chosen.

I've found this feature particularly useful when having existing overloads that take collections. Indeed, when using collection expressions (like ["a", "b"]), the compiler may find multiple applicable overloads, leading to ambiguity. By using the OverloadResolutionPriority attribute, you can guide the compiler to select the desired 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?Buy Me A Coffee💖 Sponsor on GitHub