Maintains library compatibility. Binary/source compat rules, type forwarders, SemVer impact.
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.
Scope
Binary compatibility rules (safe vs breaking changes, runtime failures)
SemVer impact mapping (change category to major/minor/patch)
Deprecation lifecycle with [Obsolete]
EnablePackageValidation and ApiCompat verification
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:
publicinterfaceIWidget
{
string Name { get; }
// Binary-safe: existing implementors inherit this defaultstring DisplayName => Name.ToUpperInvariant();
}
```text
However, if a consumer explicitly casts to the interfaceand the runtime cannot find the defaultimplementation (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 namespacetheconsumer |
| | | ` ( = )` to `` -- recompiled callers |
| { }
{ }
```text
This **source-breaking** (callers silently rebind) but **binary-compatible** (old compiled code still calls the
`` overload token).
**Mitigation:** When adding overloads to APIs, prefer parameter types that create conversion
paths existing parameter types. Use `[EditorBrowsable(EditorBrowsableState.Never)]` compatibility shims that
must remain binary compatibility but should appear IntelliSense.
Extension methods resolve at compile time based imported namespaces. Adding a extension method can shadow an
existing instance method conflict extensions other libraries:
```csharp
{
=>
s.Length <= maxLength ? s : s[..maxLength];
}
```text
**Mitigation:** Keep extension methods the same .
.
---
##
.
.
###
- ** ** ,
- ** **
- ** **
- ** **
###
** ** ( ),
:
```
;
[]
[]
[]
```text
The original assembly must reference the destination assembly so that `()` resolves correctly.
The **destination assembly** (the one types are moving TO) contains the actual type definitions. No special attributes
are needed the destination side. The `[TypeForwardedFrom]` attribute optional metadata that records the type
originally lived -- useful serialization compatibility:
```csharp
System.Runtime.CompilerServices;
;
[]
{
Name { ; ; } = .Empty;
Price { ; ; }
}
```text
`[TypeForwardedFrom]` critical types deserialized `BinaryFormatter`, `DataContractSerializer`, any
serializer that encodes assembly-qualified type names. Without it, deserialization of data written older versions
will fail `TypeLoadException`.
Type forwarders can chain: Assembly A forwards to Assembly B, which forwards to Assembly C. The runtime follows the
chain. However, =>
<PropertyGroup>
<TargetFrameworks>net8;netstandard2</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include= />
</ItemGroup>
</Project>
```csharp
See [skill:dotnet-multi-targeting] multi-TFM packaging mechanics [skill:dotnet-nuget-authoring] NuGet
packaging of forwarding shims.
---
Map API changes to Semantic Versioning increments. For full SemVer rules NuGet versioning strategies, see
[].
| Change Category | SemVer | Reason |
| ------------------------------------------------- | --------- | ----------------------------------------------------- |
| Remove type member | **Major** | Binary-breaking |
| ; signals deprecation |
| Add type | **Minor** | Additive, no breaking impact |
| ; source impact accepted at minor |
| Add optional parameter | **Minor** | Binary-compatible; recompilation picks up |
| Add DIM to | **** | -; additive |
| Change | **** | - |
| | **** | -; additive |
| Bug fix no API change | **Patch** | No API impact |
| Documentation metadata-only change | **Patch** | No API impact |
| Performance improvement same API | **Patch** | No API impact |
The standard workflow removing API members across major versions:
| Release | Action | Effect |
| ------------ | --------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| v2 (Minor) | Add `[Obsolete()]` | Compiler warning CS0618; existing code compiles runs |
| v2 (Minor) | Change to `[Obsolete(, error: )]` | Compiler error CS0619; ; consumers must migrate |
```csharp
[]
=> CalculateAsync().GetAwaiter().GetResult();
[]
=> CalculateAsync().GetAwaiter().GetResult();
```text
Always include the replacement API the planned removal version the obsolete message so both humans agents can
migrate proactively.
Adding removing target frameworks affects binary compatibility consumers:
- **Adding a TFM** (e.g., adding `net9` to an existing `net8` package): **Minor** version bump. Existing
consumers `net8` are unaffected; consumers `net9` gain optimized code paths.
- **Removing a TFM** (e.g., dropping `netstandard2`): **Major** version bump. Consumers targeting the removed TFM can
no longer resolve a compatible assembly.
- **Changing the lowest supported TFM** (e.g., `net6` to `net8`): **Major** version bump. Consumers the dropped
TFM lose compatibility.
See [skill:dotnet-multi-targeting] practical guidance managing TFM additions removals.
---
Use `EnablePackageValidation` your `.csproj` to automatically compare the current build against the previously
shipped package detect binary/source-breaking changes:
```xml
<PropertyGroup>
<EnablePackageValidation></EnablePackageValidation>
<!-- Compare against the last shipped version -->
<PackageValidationBaselineVersion></PackageValidationBaselineVersion>
</PropertyGroup>
```text
Build output flags breaking changes:
```text
error CP0002: Member was removed
error CP0006: Cannot change type of
```text
To suppress known intentional breaks, generate a suppression :
```bash
dotnet pack /p:GenerateCompatibilitySuppressionFile=
```bash
This produces a `CompatibilitySuppressions.xml` that can be checked . If unspecified, the SDK reads
`CompatibilitySuppressions.xml` the project directory automatically. To specify suppression files:
```xml
<ItemGroup>
<ApiCompatSuppressionFile Include= />
</ItemGroup>
```xml
Note: `ApiCompatSuppressionFile` an **ItemGroup item**, a PropertyGroup property. Multiple suppression files can
be included.
For deeper API surface tracking PublicApiAnalyzers CI enforcement workflows, see
[].
---
**Do assume adding an overload always safe** -- it binary-compatible but can be source-breaking due to
overload resolution changes. Always check conversion paths between existing parameter types.
**Do members without a major version bump** -- even `[Obsolete]` members must be preserved until
the next major version to maintain binary compatibility.
**Do forget type forwarders moving types between assemblies** -- without `[TypeForwardedTo]`, consumers
`TypeLoadException` at runtime. Always forwarders the original assembly.
**Do change `optional` parameter values patch releases** -- silently changes behavior
recompiled consumers old binaries retain the old , creating version-dependent behavior divergence.
**Do confuse binary compatibility source compatibility** -- a change can be binary-safe but source-breaking
( overload) source-safe but binary-breaking (changing type `` to ``). Test both.
**Do skip `[TypeForwardedFrom]` serializable types** -- serializers that encode assembly-
imports
Change
optional
parameter
default
value
Silent
behavior
change
void
Log
string
level
"info"
"debug"
get
new
default
Add member to interface (even with DIM) | CS0535 if consumer explicitly implements all members | Consumer usingexplicitinterface implementation must add the new member |
| Remove defaultvaluefromparameter (make required) | CS7036 (required argument missing) | Callers relying ondefaultvalue must now pass it explicitly |
| Add requirednamespace 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, `isnull` checks, boxing behavior | Fundamental semantic change |
| Add newnamespace 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 overloadpublicvoidSend(object message)
// V2 -- new overload; ALL callers passing string now bind here
publicvoidSend(string message)
is
object
public
do
not
implicit
from
on
for
not
in
### Extension Method Conflicts
on
new
or
with
from
// Library V1 ships in namespace MyLib.Extensions
public
static
class
StringExtensions
publicstaticstringTruncate(thisstring s, int maxLength)
// Library V2 adds to SAME namespace -- safe
// Library V2 adds to DIFFERENT namespace -- may conflict
// if consumer imports both namespaces
in
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
Forwarders
Splitting
a
large
assembly
into
smaller
focused
assemblies
Merging
assemblies
for
packaging
simplification
Reorganizing
namespaces
across
assembly
boundaries
Moving
types
to
a
shared
assembly
consumed
by
multiple
packages
Adding
Type
Forwarders
In
the
original
assembly
the
one
types
are
moving
FROM
add
forwarding
attributes
after
moving
the
types
to
the
new
assembly
csharp
// In the ORIGINAL assembly's AssemblyInfo.cs or a dedicated TypeForwarders.cs
// This tells the runtime: "Widget now lives in MyLib.Core"
keep chains short (ideally one hop) to minimize assembly loading overhead.
### Multi-TFM Type Forwarder Pattern
When restructuring assemblies in a multi-TFM library, the forwarding assembly must target all TFMs that consumers might
use. A common pattern:
```xml
<!-- Original assembly (MyLib.csproj) -- now just a forwarding shim -->
<Project Sdk
"Microsoft.NET.Sdk"
.0
.0
"../MyLib.Core/MyLib.Core.csproj"
for
and
for
## SemVer Impact Summary
and
skill:dotnet-nuget-authoring
public
or
Change method signature (return type, parameters) | **Major** | Binary-breaking |
| Add abstract member to publicclass | **Major** | Binary-breaking for subclasses |
| Add interface member without DIM | **Major** | Binary-breaking for implementors |
| Add `sealed` to a previously unsealed class | **Major** | Binary-breaking for subclasses |
| Change struct field layout | **Major** | Binary-breaking for interop consumers |
| Change namespace without type forwarder | **Major** | Binary-breaking |
| Mark member `[Obsolete]` (warning or error) | **Minor** | Binary-compatible
new
public
Add overload (may be source-breaking) | **Minor** | Binary-compatible
is
new
default
interface
Minor
Binary
compatible
namespace
WITH
type
forwarder
Minor
Binary
compatible
via
forwarding
Widen
access
modifier
Minor
Binary
compatible
with
public
or
public
with
public
### Deprecation Lifecycle with `[Obsolete]`
for
public
.1
"Use Widget.CalculateAsync() instead."
and
.3
"Use Widget.CalculateAsync() instead."
true
existing binaries still run (binary-compatible) |
| v3.0 (Major) | Remove the member entirely | Binary-breaking
// v2.1 -- warn consumers
Obsolete("Use CalculateAsync() instead. This method will be removed in v3.0.")
publicintCalculate()
// v2.3 -- block new compilation against this member
Obsolete("Use CalculateAsync() instead. This method will be removed in v3.0.", error: true)
publicintCalculate()
// v3.0 -- remove the member (Major version bump)
and
in
and
### Multi-TFM Binary Compatibility
or
for
new
.0
.0
on
.0
new
on
.0
.0
.0
.0
on
for
on
and
## Compatibility Verification
in
and
true
1.2
.0
'MyLib.Widget.Calculate()'
return
'MyLib.Widget.GetName()'
file
true
file
in
from
explicit
"CompatibilitySuppressions.xml"
is
not
with
and
skill:dotnet-api-surface-validation
## Agent Gotchas
1.
not
is
is
for
implicit
and
new
2.
not
remove
public
3.
not
when
get
add
in
4.
not
default
in
this
for
while
default
5.
not
with
new
or
return
from
int
long
6.
not
on
qualified type names
(DataContractSerializer, legacy BinaryFormatter) will fail to deserialize data written by older versions.
7. **Do not put `ApiCompatSuppressionFile` in a PropertyGroup** -- it is an ItemGroup item
(`<ApiCompatSuppressionFile Include="..." />`), not a property. Using PropertyGroup syntax silently does nothing.
8. **Do notremove a TFM from a library package without a major version bump** -- consumers on the removed TFM lose
compatibility with no fallback.
---
## Prerequisites
- .NET 8.0+ SDK
- `EnablePackageValidation` MSBuild property for automated compatibility checking
- Understanding of SemVer 2.0 conventions (see [skill:dotnet-nuget-authoring])
- Familiarity with assembly loading andbinding (strong naming concepts)
---
## References
- [Microsoft Learn: Breaking changes](https://learn.microsoft.com/dotnet/core/compatibility/categories)
- [Microsoft Learn: Type forwarding in the CLR](https://learn.microsoft.com/dotnet/framework/app-domains/type-forwarding-in-the-common-language-runtime)
- [Microsoft Learn: EnablePackageValidation](https://learn.microsoft.com/dotnet/fundamentals/apicompat/package-validation/overview)
- [.NET API compatibility analyzer](https://learn.microsoft.com/dotnet/fundamentals/apicompat/overview)
- [SemVer 2.0 Specification](https://semver.org/)
- [Library guidance: Breaking changes](https://learn.microsoft.com/dotnet/standard/library-guidance/breaking-changes)