Skip to content

Nullness bug when casting a string to an interface #18759

@charlesroddie

Description

@charlesroddie
let t1 = "" :> IEquatable<string>
// Nullness warning: A non-nullable 'string' was expected but this expression is nullable. Consider either changing the target to also be nullable, or use pattern matching to safely handle the null case of this expression.

VS 17.14.6

Misc notes:

  • The IEquatable interface unfortunately marks arguments to Equals as nullable generic mathematics interfaces should use nullable reference types runtime#73855 (comment), a wart which F# seems to squash, allowing IEquatable<'T> to be defined with Equals(y: 'T) = .... But that doesn't seem directly relevant to the above issue.
  • "" :> IEquatable<string | null> doesn't give a warning
  • A workaround is to define a wrapper [<Struct>] type StringWrapper(s: string) = member _.Value = s.
  • This applies to types where null is "allowed":
[<AllowNullLiteral>]
type NullAllowed() =
    interface IEquatable<NullAllowed> with member _.Equals(y: NullAllowed) = true
let _ = NullAllowed() :> IEquatable<NullAllowed>
// Nullness warning: The types 'IEquatable<NullStringWrapper>' and 'IEquatable<NullStringWrapper> | null' do not have compatible nullability.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    Status

    New

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions