Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Possible null reference in IEquatable implementation

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);
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading