Overload Resolution Priority in C#

HomeC#Featured

Overload Resolution Priority in C#

Casting int to enum in C#
Calling a C function from C#
Switch operator in C#

Imagine you have a method with several overloads. Sometimes, the compiler’s default rules for choosing the best overload might not align with what you, as the API designer, intended. This can lead to unexpected behavior or even breaking changes when new overloads are added.

For this C# 13 introduces the [OverloadResolutionPriority] attribute. This attribute allows you to assign a priority to different overloads of a method. The compiler will then favor overloads with higher priority when resolving method calls.

Example:

Let’s say you have a method Log with two overloads:

public void Log(string message) { /* ... */ }
public void Log(Exception exception) { /* ... */ }

Without any intervention, calling Log(“Something happened”) might now resolve to the new overload with a null exception parameter, instead of the original Log(string message) overload. This could be a breaking change for existing code.

To prevent this, you can use the [OverloadResolutionPriority] attribute:

[OverloadResolutionPriority(1)]
public void Log(string message) { /* ... */ }

[OverloadResolutionPriority(1)]
public void Log(Exception exception) { /* ... */ }

[OverloadResolutionPriority(2)]
public void Log(string message, Exception exception) { /* ... */ }

By giving the new overload a higher priority, you ensure that it’s chosen only when both a message and an exception are provided.

Higher priority wins: Overloads with higher numerical values for the attribute are preferred.
Default priority: If no attribute is specified, the overload has a default priority of 0.
Breaking changes: This feature helps avoid accidental breaking changes when adding new overloads to existing libraries.
Library design: It gives library authors more control over how their APIs are used.

COMMENTS

DISQUS: 0