Claude
Skills
Sign in
Back

dotnet-library-api-compat

Included with Lifetime
$97 forever

Maintaining library compatibility. Binary/source compat rules, type forwarders, SemVer impact.

Backend & APIs

What this skill does


# dotnet-library-api-compat

Binary and source compatibility rules for .NET library authors. Covers which API changes break consumers at the binary level (assembly loading, JIT resolution) versus at the source level (compilation), how to use type forwarders for assembly reorganization without breaking consumers, and how versioning decisions map to SemVer major/minor/patch increments.

**Version assumptions:** .NET 8.0+ baseline. Compatibility rules apply to all .NET versions but examples target modern SDK-style projects.

**Out of scope:** HTTP API versioning -- see [skill:dotnet-api-versioning]. NuGet package metadata, signing, and publish workflows -- see [skill:dotnet-nuget-authoring]. Multi-TFM packaging mechanics (polyfill strategy, conditional compilation) -- see [skill:dotnet-multi-targeting]. PublicApiAnalyzers and API surface validation tooling -- see [skill:dotnet-api-surface-validation]. Roslyn analyzer configuration -- see [skill:dotnet-roslyn-analyzers].

Cross-references: [skill:dotnet-api-versioning] for HTTP API versioning, [skill:dotnet-nuget-authoring] for NuGet packaging and SemVer rules, [skill:dotnet-multi-targeting] for multi-TFM packaging and ApiCompat tooling.

---

## Binary Compatibility

Binary compatibility means existing compiled assemblies continue to work at runtime without recompilation. A binary-breaking change causes `TypeLoadException`, `MissingMethodException`, `MissingFieldException`, or `TypeInitializationException` at runtime.

### Safe Changes (Binary Compatible)

| Change | Why Safe |
|--------|----------|
| Add new public type | Existing code never references it |
| Add new public method to non-sealed class | Existing call sites resolve to their original overload |
| Add new overload with different parameter count | Existing binaries bind to the original method token |
| Add optional parameter to existing method | Callers compiled against the old signature have default values embedded in their IL; the runtime resolves the same method token regardless of whether the optional parameter is supplied |
| Widen access modifier (`protected` to `public`) | Existing references remain valid at higher visibility |
| Add non-abstract interface member with default implementation | Existing implementors inherit the default; no `TypeLoadException` |
| Remove `sealed` from class | Removes a restriction; existing code never subclassed it |
| Add new `enum` member | Existing binaries that switch on the enum simply fall through to `default` |

### Breaking Changes (Binary Incompatible)

| Change | Runtime Failure | Example |
|--------|----------------|---------|
| Remove public type | `TypeLoadException` | Delete `public class Widget` |
| Remove public method | `MissingMethodException` | Remove `Widget.Calculate()` |
| Change method return type | `MissingMethodException` | `int Calculate()` to `long Calculate()` |
| Change method parameter types | `MissingMethodException` | `void Process(int id)` to `void Process(long id)` |
| Change field type | `MissingFieldException` | `public int Count` to `public long Count` |
| Reorder struct fields | Memory layout change | Breaks interop and `Unsafe.As<>` consumers |
| Add abstract member to public class | `TypeLoadException` | Existing subclasses lack the implementation |
| Add interface member without default implementation | `TypeLoadException` | Existing implementors lack the member |
| Change `virtual` method to `non-virtual` | `MissingMethodException` for overriders | Overriders compiled expecting virtual dispatch |
| Seal a previously unsealed class | `TypeLoadException` | Existing subclasses cannot load |
| Change namespace of public type | `TypeLoadException` | Unless a type forwarder is added (see below) |
| Remove `virtual` from a method | `MissingMethodException` | Consumers compiled with `callvirt` find no virtual slot |

### Default Interface Members

Default interface members (DIM) added in C# 8 allow adding members to interfaces without breaking existing implementors -- **but only at the binary level**:

```csharp
public interface IWidget
{
    string Name { get; }

    // Binary-safe: existing implementors inherit this default
    string DisplayName => Name.ToUpperInvariant();
}
```

However, if a consumer explicitly casts to the interface and the runtime cannot find the default implementation (older runtime), this fails. All runtimes in the .NET 8.0+ baseline support DIMs.

---

## Source Compatibility

Source compatibility means existing consumer code continues to compile without changes. A source-breaking change causes compiler errors or changes behavior silently (which is worse).

### Common Source-Breaking Changes

| Change | Compiler Impact | Example |
|--------|----------------|---------|
| Add overload causing ambiguity | CS0121 (ambiguous call) | Add `Process(long id)` when `Process(int id)` exists; callers passing `int` literal now have two candidates |
| Add extension method conflicting with instance method | New extension hides or conflicts | Adding `Where()` extension in a namespace the consumer imports |
| Change optional parameter default value | Silent behavior change | `void Log(string level = "info")` to `"debug"` -- recompiled callers get new default |
| Add member to interface (even with DIM) | CS0535 if consumer explicitly implements all members | Consumer using explicit interface implementation must add the new member |
| Remove default value from parameter (make required) | CS7036 (required argument missing) | Callers relying on default value must now pass it explicitly |
| Add required namespace import | CS0246 if consumer does not import | New public types in consumer's namespace collide |
| Change parameter name | Breaks callers using named arguments | `Process(id: 5)` fails if parameter renamed to `identifier` |
| Change `class` to `struct` (or vice versa) | Breaks `new()` constraints, `is null` checks, boxing behavior | Fundamental semantic change |
| Add new namespace that collides with existing type names | CS0104 (ambiguous reference) | Adding `MyLib.Tasks` namespace conflicts with `System.Threading.Tasks` |

### Overload Resolution Pitfalls

Adding overloads is the most common source of source-breaking changes in libraries. The C# compiler picks the "best" overload at compile time, and a new overload can change which method wins:

```csharp
// V1 -- only overload
public void Send(object message) { }

// V2 -- new overload; ALL callers passing string now bind here
public void Send(string message) { }
```

This is **source-breaking** (callers silently rebind) but **binary-compatible** (old compiled code still calls the `object` overload token).

**Mitigation:** When adding overloads to public APIs, prefer parameter types that do not create implicit conversion paths from existing parameter types. Use `[EditorBrowsable(EditorBrowsableState.Never)]` on compatibility shims that must remain for binary compatibility but should not appear in IntelliSense.

### Extension Method Conflicts

Extension methods resolve at compile time based on imported namespaces. Adding a new extension method can shadow an existing instance method or conflict with extensions from other libraries:

```csharp
// Library V1 ships in namespace MyLib.Extensions
public static class StringExtensions
{
    public static string Truncate(this string s, int maxLength) =>
        s.Length <= maxLength ? s : s[..maxLength];
}

// Library V2 adds to SAME namespace -- safe
// Library V2 adds to DIFFERENT namespace -- may conflict
// if consumer imports both namespaces
```

**Mitigation:** Keep extension methods in the same namespace across versions. Document any namespace additions in release notes.

---

## Type Forwarders

Type forwarders allow moving a public type from one assembly to another without breaking existing compiled references. The original assembly contains a forwarding entry that redirects the runtime type resolver to the new location.

### When to Use Type Forwarde

Related in Backend & APIs