Skip to content

NullReferenceException from Token.operator != #1797

Closed
@KalleOlaviNiemitalo

Description

@KalleOlaviNiemitalo

If operator ==(Token left, Token right) or operator !=(Token left, Token right) is called such that left is null, then it throws NullReferenceException because it tries to call left.Equals(right).

/// <summary>
/// Checks if two specified <see cref="Token"/> instances have the same value.
/// </summary>
/// <param name="left">The first <see cref="Token"/>.</param>
/// <param name="right">The second <see cref="Token"/>.</param>
/// <returns><see langword="true" /> if the objects are equal.</returns>
public static bool operator ==(Token left, Token right) => left.Equals(right);
/// <summary>
/// Checks if two specified <see cref="Token"/> instances have different values.
/// </summary>
/// <param name="left">The first <see cref="Token"/>.</param>
/// <param name="right">The second <see cref="Token"/>.</param>
/// <returns><see langword="true" /> if the objects are not equal.</returns>
public static bool operator !=(Token left, Token right) => !left.Equals(right);

That happened in my app, which compared optionResult.Token != null as part of the #1795 (comment) implementation. I'll be able to work around the bug by using !object.ReferenceEquals(optionResult.Token, null) instead.

No other types in System.CommandLine define comparison operators that could have similar bugs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions