The API files

edit

An API file is a C# file that declares the public API of an assembly, with stubs in place of the bodies. For this code:

namespace Demo;

public enum Unit
{
    Celsius,
    Fahrenheit,
    Kelvin = 10,
}

public sealed class Thermometer : IComparable<Thermometer>
{
    private double _value;

    public Thermometer(string name) => Name = name;

    public string Name { get; private set; }
    public string? Location { get; set; }
    public event EventHandler? Changed;

    public double Read(Unit unit = Unit.Celsius) => _value;
    public void Rename(string name) { Name = name; Changed?.Invoke(this, EventArgs.Empty); }
    internal void Calibrate(double value) => _value = value; // Not visible outside the assembly
    public int CompareTo(Thermometer? other) => 0;
}

The generator writes:

// Target Frameworks: net10.0
#nullable enable

namespace Demo
{
    public sealed class Thermometer : System.IComparable<global::Demo.Thermometer>
    {
        public string? Location { get => throw null; set { } }
        public string Name { get => throw null; }
        public event System.EventHandler? Changed;
        public Thermometer(string name) { }
        public int CompareTo(global::Demo.Thermometer? other) => throw null;
        public double Read(global::Demo.Unit unit = global::Demo.Unit.Celsius) => throw null;
        public void Rename(string name) { }
    }

    public enum Unit
    {
        Celsius = 0,
        Fahrenheit = 1,
        Kelvin = 10,
    }
}

What a file contains

  • A header: a // <auto-generated/> comment (omitted in the example above, see the options), the target frameworks of the assembly, optionally the referenced assemblies, then #nullable enable.
  • The public API: the types and members that are visible outside the assembly (public, protected and protected internal), and the explicit implementations of public interfaces. Private and internal members, accessors that are not visible (such as a private set), static constructors and compiler-generated types are not in the file.
  • The details of each declaration: modifiers, nullable annotations, default values of parameters, generic constraints, values of the enum members, and attributes such as [SupportedOSPlatform("windows")]. See Attributes for the attributes that are written.
  • Stubs: a method or a property getter that returns a value is => throw null;, the others are { }.
  • Fully qualified type names: the file has no using directive, so a type name never depends on the context. global:: is added where a name could be ambiguous.

The new modifier is not stored in the assembly: the generator adds it to the members that hide an inherited member, using the rules of the C# compiler. See The new modifier.

Extension members

The members of C# 14 extension blocks are written in extension blocks, as in the source code. For this code:

namespace Demo;

public static class StringExtensions
{
    extension(string value)
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(value);
        public string Repeat(int count) => string.Concat(Enumerable.Repeat(value, count));
    }

    extension(string)
    {
        public static string Concatenate(params IEnumerable<string> values) => string.Concat(values);
    }
}

The generator writes:

// Target Frameworks: net10.0
#nullable enable

namespace Demo
{
    public static class StringExtensions
    {
        extension(string value)
        {
            public bool IsBlank { get => throw null; }
            public string Repeat(int count) => throw null;
        }
        extension(string)
        {
            public static string Concatenate(params System.Collections.Generic.IEnumerable<string> values) => throw null;
        }
    }
}
  • One block per receiver: the compiler merges the blocks that declare the same receiver (same type, name, modifiers, attributes and type parameters), so the generator writes them as one block, whatever their order in your code. Two blocks whose receivers differ, such as extension(string value) and extension(string), stay apart.
  • The blocks are after the other members of the class, sorted by the type of the receiver, then by their text. The members of a block are sorted as the other members.
  • All the members are in their block: methods, properties and operators, instance and static. The methods the compiler generates for them, such as Repeat(this string value, int count) or get_IsBlank(string), are not in the file. A classic extension method, declared outside of an extension block, is written as declared.
  • Multi-targeted libraries: a member that is not in every target framework is wrapped in an #if block inside its extension block, not the whole block.

File layouts

The API can be written to one file or split into several files. The layout is an option of the MSBuild package, of the tool and of the library:

LayoutFiles
SingleFile (default)One file for the whole assembly. The tool and the library name it <AssemblyName>.cs; the MSBuild package writes it at the path you set.
OneFilePerNamespaceOne file per namespace: Demo.g.cs, and GlobalNamespace.g.cs for the types that have no namespace.
OneFilePerTypeOne file per top-level type, named after its full name: Demo.Thermometer.g.cs. Nested types are in the file of their containing type.

When the files have assembly attributes ([RequiresPreviewFeatures], or the ones written with the option that writes all the attributes), the OneFilePerNamespace and OneFilePerType layouts also write an AssemblyInfo.g.cs file that declares them.

When two files would have the same name, ignoring case, the names are made distinct so that the files are the same on every file system. The files are sorted by name, ordinally: the first one keeps its name, and the next ones get a ~2, ~3... suffix. For instance, the types Demo.Foo and Demo.foo are written to Demo.Foo.g.cs and Demo.foo~2.g.cs. A C# name cannot contain ~, so the suffix never gives the name of another file.

A single file is the easiest to review and to check. The other layouts make diffs easier to read for a large API, but the files of the types or namespaces you remove stay on disk unless you turn on the option that deletes them: see Files of removed types.

Order of the declarations

The output only depends on the public API: moving a declaration in the source code, or to another file of a partial type, does not change it.

  • Namespaces and types are sorted by name.
  • Members are grouped by kind: fields, properties and indexers, events, constructors, destructors, methods, operators, then conversion operators. In a group, members are sorted by name, then by number of generic parameters, number of parameters, and types of the parameters. An explicit interface implementation is sorted by the name of the member, then by the name of the interface.
  • Enum members are sorted by value, then by name.
  • Interfaces, attributes and named arguments of attributes are sorted by name. The constraints of a generic parameter are sorted by name, after the base type.

All comparisons are ordinal.

Multi-targeted libraries

The builds of a library for several target frameworks are merged into one set of files. The declarations that are not the same in every target framework are wrapped in #if blocks, using the preprocessor symbol of each target framework (NET10_0, NETSTANDARD2_0...). For this code, built for netstandard2.0 and net10.0:

namespace Demo;

public readonly struct Temperature : IFormattable
#if NET10_0_OR_GREATER
    , ISpanFormattable
#endif
{
    public Temperature(double celsius) => Celsius = celsius;

    public double Celsius { get; }

    public string ToString(string? format, IFormatProvider? formatProvider) => Celsius.ToString(format, formatProvider);

#if NET10_0_OR_GREATER
    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
        => Celsius.TryFormat(destination, out charsWritten, format, provider);
#endif
}

The generator writes:

// Target Frameworks: net10.0, netstandard2.0
#nullable enable

namespace Demo
{
    public readonly struct Temperature : System.IFormattable
    #if NET10_0
        , System.ISpanFormattable
    #endif
    {
        public double Celsius { get => throw null; }
        public Temperature(double celsius) { }
        public string ToString(string? format, System.IFormatProvider? formatProvider) => throw null;
        #if NET10_0
        public bool TryFormat(System.Span<char> destination, out int charsWritten, System.ReadOnlySpan<char> format, System.IFormatProvider? provider) => throw null;
        #endif
    }
}

Conditional blocks are kept as narrow as possible, so that adding a target framework produces a small diff. A type stays unconditional when the target frameworks only differ by its attributes, its members or its base type list: only the parts that are not shared by every target framework are wrapped. The whole type is wrapped only when it cannot be merged, for instance when it does not exist in every target framework, or when its modifiers or generic constraints differ.

The MSBuild package merges all the target frameworks of the project automatically. With the tool and the library, pass the build of each target framework.

Attributes

By default, the files contain the attributes of the System namespaces that change how the API is used, such as [Obsolete], [SupportedOSPlatform("windows")] or [NotNullWhen(true)], and [RequiresPreviewFeatures] on the assembly. Other attributes are part of the API contract too: turn on the option that writes all the attributes (PublicApiGeneratorIncludeAllAttributes with the MSBuild package, --include-all-attributes with the tool, or IncludeAllAttributes with the library). For this code:

using System.ComponentModel;

[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://example.com/demo")]

namespace Demo;

[AttributeUsage(AttributeTargets.All)]
public sealed class StableAttribute : Attribute;

public sealed class Thermometer
{
    [Stable]
    public double Read() => 0;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public void Calibrate(double value) { }
}

The generator writes:

// Target Frameworks: net10.0
[assembly: System.Reflection.AssemblyMetadata("RepositoryUrl", "https://example.com/demo")]
#nullable enable

namespace Demo
{
    [System.AttributeUsage(System.AttributeTargets.All)]
    public sealed class StableAttribute : System.Attribute
    {
    }

    public sealed class Thermometer
    {
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public void Calibrate(double value) { }
        [global::Demo.Stable]
        public double Read() => throw null;
    }
}

The option adds:

  • [EditorBrowsable], which hides members from IntelliSense.
  • The attributes of other namespaces than System, such as the attributes your library declares. An attribute declared in the assembly is written only when the files declare what its usage needs: a public type and a public constructor. An attribute whose type is nested or generic is not written. The visibility of the attributes declared in other assemblies is not checked.
  • Parameterless constructors that have attributes to write. Without the option, a public parameterless constructor is omitted, as it declares the same API as the implicit one.
  • The assembly attributes, such as [InternalsVisibleTo], [AssemblyMetadata] or [CLSCompliant], except the ones that the SDK generates from the properties of the project ([AssemblyCompany], [AssemblyProduct], the versions, [TargetFramework]...): they change from one build to another, or would be declared twice when compiling the files.

Some attributes are never written:

  • The attributes represented by the C# syntax, such as NullableAttribute (string?), ExtensionAttribute (this), IsReadOnlyAttribute (readonly), ParamArrayAttribute (params) or TupleElementNamesAttribute. The compiler rejects most of them when they are written explicitly.
  • The attributes that describe the implementation, such as [CompilerGenerated], [AsyncStateMachine], [DebuggerStepThrough] or [GeneratedCode].

Referenced assemblies

A change of dependency does not always change the public API: a new package can be used only by the implementation. To see it in the API files, turn on the list of the referenced assemblies (PublicApiGeneratorIncludeAssemblyReferences with the MSBuild package, --include-assembly-references with the tool, or IncludeAssemblyReferences with the library). For this code, whose project references the Demo.Core project:

namespace Demo;

// Demo.Core is a project reference: it is listed in Demo.deps.json, the assemblies of .NET are not
public sealed class Thermometer
{
    public Demo.Core.Temperature Read() => new(21.5);
    public HttpClient? Client { get; set; }
}

The header lists Demo.Core, but not System.Net.Http nor System.Runtime, which come from .NET:

// Target Frameworks: net10.0
// Assembly References:
//   Demo.Core
#nullable enable

namespace Demo
{
    public sealed class Thermometer
    {
        public System.Net.Http.HttpClient? Client { get => throw null; set { } }
        public global::Demo.Core.Temperature Read() => throw null;
    }
}
  • The generator reads the .deps.json file that the SDK writes next to the assembly (Demo.deps.json for Demo.dll). It lists the packages, the project references and the referenced files, not the assemblies of the framework. A referenced assembly that it does not list is not written.
  • Without a .deps.json file (an assembly copied without it, or an Assembly loaded in the process whose directory has none), every referenced assembly is written, including System.Runtime or netstandard.
  • The include patterns add assemblies of the framework to the list, and the exclude patterns remove any assembly. An exclude pattern wins over an include pattern. A pattern is a name that can contain * (any characters) and ? (one character), compared without case, for instance System.Net.*.
  • The compiler only keeps the references the code uses, so a package that is referenced by the project but not used by the code is not listed.
  • The list contains the names of the assemblies, not their versions, so updating a package does not change the file.
  • An assembly that only some target frameworks reference is followed by these target frameworks.
  • With the OneFilePerNamespace and OneFilePerType layouts, the list is only in AssemblyInfo.g.cs, which exists even when the assembly has no assembly-level attribute.

Compiling the files

The files are valid C#, so you can compile them, for instance to check that they are consistent. Two settings of the project that compiles them matter:

  • Nullable annotations: the files start with #nullable enable.
  • Memory safety rules: for an assembly compiled with the updated memory safety rules (<Features>$(Features);updated-memory-safety-rules</Features>), the unsafe modifier is written on the members the compiler marked as requiring an unsafe context, whatever their signature: pointers in a signature no longer imply unsafe, and delegate declarations are never unsafe. Compiling these files may need the same feature. For other assemblies, a member is unsafe when a pointer type appears in its signature, which matches the compatibility mode of the compiler.

Do not compile the API files into the library they describe: every type would be declared twice. See Getting started.