❔ Nullability issue

I have this code
public bool Equals(Money money)
{
if (money is null)
{
return false;
}

if (ReferenceEquals(this, money))
{
return true;
}

return Currency.CurrencyCode == money.Currency.CurrencyCode && Amount == money.Amount;
}
public bool Equals(Money money)
{
if (money is null)
{
return false;
}

if (ReferenceEquals(this, money))
{
return true;
}

return Currency.CurrencyCode == money.Currency.CurrencyCode && Amount == money.Amount;
}
and i get this warning. How can i fix it?
10 Replies
Angius
Angius2y ago
IEquatable has method .Equals() that takes a nullable parameter So just change Equals(Money money) to Equals(Money? money)
_giuraemanuel
_giuraemanuel2y ago
Hey. Thanks for your answer! But Money can't be null whatsoever so how does that help? Sorry if my question is dumb.
Angius
Angius2y ago
IEquatable requires the method Equals() to also handle a null That's all there is to it
_giuraemanuel
_giuraemanuel2y ago
Hmm. Okay. Thank you!
Angius
Angius2y ago
A class implementing an interface must implement it entirely and verbatim
_giuraemanuel
_giuraemanuel2y ago
Fair enough. I wasn't exactly familiar with equality implementation and stuff so that's why i asked. Thanks once again!
Angius
Angius2y ago
Anytime 👌
Sagar viradiya
@GEmanuel Can you share updated code.
_giuraemanuel
_giuraemanuel2y ago
public bool Equals(Money? money)
{
if (money is null)
{
return false;
}

if (ReferenceEquals(this, money))
{
return true;
}

return Currency.CurrencyCode == money.Currency.CurrencyCode && Amount == money.Amount;
}

public override bool Equals(object? obj)
{
return obj is Money money && Equals(money);
}

public override int GetHashCode()
{
int hash = 17;
hash = hash * 23 + Currency.GetHashCode();
hash = hash * 23 + Amount.GetHashCode();
return hash;
}
}
public bool Equals(Money? money)
{
if (money is null)
{
return false;
}

if (ReferenceEquals(this, money))
{
return true;
}

return Currency.CurrencyCode == money.Currency.CurrencyCode && Amount == money.Amount;
}

public override bool Equals(object? obj)
{
return obj is Money money && Equals(money);
}

public override int GetHashCode()
{
int hash = 17;
hash = hash * 23 + Currency.GetHashCode();
hash = hash * 23 + Amount.GetHashCode();
return hash;
}
}
Sorry for the late reply. Here you go. Based on this: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type
How to define value equality for a class or struct - C# Programming...
Learn how to define value equality for a class or struct. See code examples and view available resources.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity. Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.