0

I'm trying to find out how to remove that possible null reference in the IEquatable implementation below.

return other != null && _guid == other._guid; Possible null reference argument for parameter 'left' in 'bool SubscriptionToken.operator !=(SubscriptionToken left, SubscriptionToken right)'

public class SubscriptionToken : IEquatable<SubscriptionToken>
{
    public static readonly SubscriptionToken Empty = new(Guid.Empty);

    private readonly Guid _guid;

    private SubscriptionToken(Guid guid)
    {
        _guid = guid;
    }

    private SubscriptionToken()
    {
    }

    public Guid Value => _guid;

    public bool Equals(SubscriptionToken? other)
    {
        return other != null && _guid == other._guid; // Possible null reference
    }

    public bool IsValid()
    {
        return _guid != Guid.Empty;
    }

    public static SubscriptionToken New()
    {
        return new SubscriptionToken(Guid.NewGuid());
    }

    public override bool Equals(object? other)
    {
        return other is SubscriptionToken token && Equals(token);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(_guid);
    }

    public override string ToString()
    {
        return _guid.ToString("N");
    }

    public static bool operator ==(SubscriptionToken left, SubscriptionToken right)
    {
        return EqualityComparer<SubscriptionToken>.Default.Equals(left, right);
    }

    public static bool operator !=(SubscriptionToken left, SubscriptionToken right)
    {
        return !(left == right);
    }
}
nop
  • 4,711
  • 6
  • 32
  • 93

1 Answers1

1

Your equals method should probably look something like this:

        public bool Equals(SubscriptionToken other)
        {
            if (ReferenceEquals(null, other)) return false;
            return _guid.Equals(other._guid);
        }

That should avoid any null reference exceptions.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • `public bool Equals(SubscriptionToken? other) { return other is not null && _guid.Equals(other._guid); } `, the IDE corrected `ReferenceEquals` to the `is not null` pattern – nop Jun 09 '22 at 07:48
  • 1
    @nop that is fine. I'm not running the latest c# version. – JonasH Jun 09 '22 at 08:04