skip to content

In a C# library, how do you deprecate an old LogAsync overload with [Obsolete] and ship a preview API with [Experimental], and what do callers' builds report?

level: seniorimportance: should knowfreq 35%

answer

  1. warning first, error later
  2. a diagnostic id of your own
  3. evaluation-only means opt in
  4. suppress by that exact id

basics

~20 s

Mark the old overload [Obsolete("use X")] for warning CS0618, or error: true for CS0619; DiagnosticId and UrlFormat give it your own id and link. [Experimental("ID")], since .NET 8, makes each use a build error under that id until the caller suppresses it.

solid answer

~40 s

`[Obsolete]` is read by the C# compiler at each use: with no message it is warning CS0612, with a message CS0618, and with `error: true` it is error CS0619. Setting `DiagnosticId = "OBS0001"` replaces the CS id so callers can suppress just your deprecation, and `UrlFormat` appends a link with `{0}` filled by that id. A typical path is warning in one minor release, error in the next, removal in a major one. `[Experimental("OBSEXP01")]` from `System.Diagnostics.CodeAnalysis` (.NET 8, C# 12) works the same way for APIs that are not stable yet, but each use is an **error** by default; callers opt in by suppressing that id with `NoWarn` or `#pragma warning disable`. Uses from inside another obsolete or experimental member are not reported, and an error-level `[Obsolete]` cannot be suppressed by `#pragma`.

code

csharp · 25 lines
csharp
using System.Diagnostics.CodeAnalysis;

var tracer = new Tracer();
await tracer.LogAsync("order placed");                                // OBS0001 warning
await tracer.LogAsync("order placed", CancellationToken.None);       // fine
tracer.Flush();                                                        // CS0619 error
var policy = new SamplingPolicy(0.1);                                  // OBSEXP01 error

public sealed class Tracer
{
    [Obsolete("Use LogAsync(string, CancellationToken).", DiagnosticId = "OBS0001",
        UrlFormat = "https://example.com/obs/{0}")]
    public Task LogAsync(string message) => LogAsync(message, CancellationToken.None);

    public Task LogAsync(string message, CancellationToken ct) => Task.CompletedTask;

    [Obsolete("Flush is gone; dispose the Tracer instead.", error: true)]
    public void Flush() { }
}

[Experimental("OBSEXP01")]
public sealed class SamplingPolicy(double rate)
{
    public double Rate { get; } = rate;
}

go deeper

for a junior

Know that [Obsolete] makes the compiler warn at each use, and that a message telling callers what to use instead belongs in the attribute.

for a middle

Distinguish CS0612, CS0618 and CS0619, and explain that both attributes are read by the caller's compiler, not at run time.

for a senior

Plan a deprecation with a custom DiagnosticId and UrlFormat, flip to error before removal, and ship preview APIs with per-feature [Experimental] ids that callers suppress explicitly.

for a principal

Set a library's API lifecycle policy: how many releases a deprecation warns before erroring, how experimental ids are named, and how consumers are told to opt in.

## Two attributes the compiler enforces Both attributes are metadata on the library's API that the **C# compiler of the consuming project** reads whenever code references the marked symbol. No reflection is involved and nothing happens at run time: the effect is a diagnostic in the caller's build. | | `[Obsolete]` (`System.ObsoleteAttribute`) | `[Experimental]` (`System.Diagnostics.CodeAnalysis.ExperimentalAttribute`) | |---|---|---| | Purpose | the API is going away or is discouraged | the API is usable but not stable yet | | Default severity | warning | error | | Default id | CS0612 (no message), CS0618 (message), CS0619 (`error: true`) | none: the constructor requires your `diagnosticId` | | Custom id | `DiagnosticId` property | the constructor argument | | Link | `UrlFormat`, `{0}` replaced by the id | `UrlFormat` in the current .NET 10 library | | Available since | every supported .NET version | .NET 8, recognized by the C# 12 compiler | ## Deprecating LogAsync with [Obsolete] ```csharp [Obsolete("Use LogAsync(string, CancellationToken).", DiagnosticId = "OBS0001", UrlFormat = "https://example.com/obs/{0}")] public Task LogAsync(string message) => LogAsync(message, CancellationToken.None); ``` A caller of the old overload now sees `warning OBS0001: 'Tracer.LogAsync(string)' is obsolete: 'Use LogAsync(string, CancellationToken).' (https://example.com/obs/OBS0001)`. The pieces: - **Message**: say what to use instead. `nameof` and constant interpolation keep the replacement's name correct after refactoring. - **`error: true`**: turns the use into a compile error, CS0619 or your custom id. A `#pragma warning disable` cannot suppress it; the caller must change code. - **`DiagnosticId`**: without it every deprecation in every library shares CS0618, so a team that silences CS0618 to quiet one noisy dependency silences yours too, and nobody can silence yours alone. With it, `NoWarn` for `CS0618` no longer hides your warning, and `NoWarn` for `OBS0001` hides only it. - **`UrlFormat`**: one page per id explaining the migration. A common lifecycle: 1. Version N: add the replacement and mark the old member obsolete as a warning with an id and link. 2. Version N+1: flip to `error: true` so remaining callers must migrate, while the member still exists for binary compatibility with already compiled code. 3. Next major version: delete it. Callers that build with `TreatWarningsAsErrors` hit step 1 as a build break, which is one reason the warning stage should come with a clear message and link. ## Shipping a preview API with [Experimental] ```csharp [Experimental("OBSEXP01")] public sealed class SamplingPolicy(double rate) { ... } ``` Any reference to `SamplingPolicy` reports `error OBSEXP01: 'SamplingPolicy' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.` The compiler's internal name for this diagnostic starts with WRN and some docs pages call it a warning, but the SDK 10.0.401 compiler reports it as an **error** until it is suppressed, matching the .NET preview-APIs guidance. Opting in is per id, so consenting to one experimental feature does not consent to another: - project-wide: `<NoWarn>$(NoWarn);OBSEXP01</NoWarn>` (the recommended route); - locally: `#pragma warning disable OBSEXP01` around the call. `[Experimental]` can also be put on an assembly or module, which makes every type in it experimental. Libraries targeting frameworks older than .NET 8 can declare an internal copy of the attribute in the same namespace for the C# 12 or later compiler to honour; that polyfill technique belongs with language-version targeting. ## Reading the build output The example's three marked uses produce three different diagnostics in one build: - line 4, the old `LogAsync(string)`: a **warning** under the custom id `OBS0001`, with the link built from `UrlFormat`; the build would still succeed on this alone; - line 6, `Flush()` marked `error: true` without a custom id: **error CS0619**; - line 7, `new SamplingPolicy(0.1)`: **error OBSEXP01**, the experimental id. The call on line 5 to the new overload is clean, which is the point of a deprecation message that names its replacement. ## Propagation inside the library The compiler does not report uses that sit inside a member that is itself marked the same way: an `[Obsolete]` helper may call another obsolete member, and an `[Experimental]` method may use another experimental API, without diagnostics. That lets you build a preview feature from experimental pieces and mark only the entry points callers touch. Both attributes are declared `Inherited = false`, so reflection does not report them on overrides. ## Choosing between them Both are promises to consumers about change, so the choice turns on the direction of travel: - The API exists and is stable, but you want callers off it: `[Obsolete]`, warning then error. - The API is new and its shape may still change in a stable package: `[Experimental]` with a feature-specific id. - A whole package is preview: a prerelease package version already says so, without either attribute.

  • Why give [Obsolete] a DiagnosticId instead of relying on CS0618?
    CS0618 is shared by every deprecation in every library. A caller who suppresses it for one dependency hides all of them, and cannot silence only yours. With `DiagnosticId = "OBS0001"` the warning carries your id, `NoWarn` for CS0618 no longer hides it, and `UrlFormat` can point to a migration page for exactly that id.
  • How does a consuming team opt in to an API marked [Experimental("OBSEXP01")]?
    By suppressing that specific id: `<NoWarn>$(NoWarn);OBSEXP01</NoWarn>` in the project file, which the .NET guidance recommends, or `#pragma warning disable OBSEXP01` around the use. Code inside a member that is itself marked with the same experimental attribute is not reported either. Each experimental feature has its own id, so the opt-in is per feature.
  • Can a caller suppress an [Obsolete] marked error: true with #pragma?
    No. With `error: true` the use is a compile error, CS0619 or the custom `DiagnosticId`, and `#pragma warning disable` only affects warnings; the SDK still fails the build. The caller has to move to the replacement, or the call has to sit inside a member that is itself marked `[Obsolete]`, where the compiler does not report it.

  • Thinks [Experimental] only produces a warning that callers can ignore
  • Believes NoWarn for CS0618 also hides an obsolete warning that has a custom DiagnosticId
  • Removes an API outright instead of moving it from warning to error first
  • Expects #pragma warning disable to silence an [Obsolete] marked error: true
  • Thinks [Obsolete] is checked at run time when the method is called
  • Uses EnablePreviewFeatures to opt in to an API marked [Experimental]