Skip to content

Incorrect nullable annotations on most MemoryExtensions methods #73457

@stephentoub

Description

@stephentoub

Most of our MemoryExtensions methods have a shape like:

public static bool Contains<T>(this Span<T> span, T value) where T : IEquatable<T>

where the T is constrained to be IEquatable<T>. The questionable nature of the constraint in general aside (we can use EqualityComparer<T>.Default), the constraint is too strict with regards to nullable reference types. The constraint should be where T : IEquatable<T>? rather than where T : IEquatable<T>; otherwise, it's prohibiting nullable Ts, e.g. this erroneously warns:

Span<string?> objects = new string?[] { "hello", null, "world" };
Console.WriteLine(objects.Contains(null));

with:

warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'MemoryExtensions.Contains<T>(Span<T>, T)'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'.

We need to audit all such constraints and fix them.

cc: @terrajobst, @bartonjs, @jeffhandley

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions