Skip to content

APIs that could use annotations or attributes for nullability #28086

@jcouv

Description

@jcouv

In C# 8.0 with the nullability analysis turned on, libraries that don't carry explicit nullable annotations are treated as "oblivious", which means the analysis assumes the best (to minimize nullability warnings).

This is generally a reasonable assumption, but it hides some potentially useful warnings. As a rule of thumb:

  • any API which could return a null should declare that.
  • any API which throws an exception on a null input should declare that. For instance, Path.GetDirectoryName(string! name).

The experience of using nullability analysis on APIs can be further enhanced with some attributes that provide hints about the semantics of the API:

  • bool string.IsNullOrEmpty([NotNullWhenFalse] string value)
  • bool string.IsNullOrWhiteSpace([NotNullWhenFalse] string value)
  • [MaybeNull] T FirstOrDefault(...)
  • Debug.Assert([EnsuresTrue] ...)

We are still working to finalize the set of such attributes (tracked by dotnet/roslyn#26761).

I'm opening this issue to collect such examples, so that we have some idea which APIs should be annotated first, once we are ready to do that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-MetaenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions