Let's start with a very simple piece of code:
decimal d = 2;
Console.WriteLine("d == 2 = {0}", d == 2);
Console.WriteLine("d == (decimal)2 = {0}", d == (decimal)2);
Console.WriteLine("d.Equals(2) = {0}", d.Equals(2));
Console.WriteLine("d.Equals((decimal)2) = {0}", d.Equals((decimal)2));
The result is 4xtrue. Now, let's change a type of a variable d to decimal?:
decimal? d = 2;
This time the result will be True, True, False, True. The explanation of this situation is quite easy. Equals method is implemented as follows for Nullable<T> type:
public override bool Equals(object other)
{
if (!this.HasValue)
{
return (other == null);
}
if (other == null)
{
return false;
}
return this.value.Equals(other);
}
If this has a value and other parameter is not null then Decimal.Equals(object value) will be called. Decimal.Equals(object value) method works in this way, that if value parameter is not decimal then the result will be always false.
It seems to me that the current implementation is not intuitive and I wonder why Nullable<T> doesn't provide developers with generic version of Equals method e.g.:
public bool Equals(T other)
{
if (!this.HasValue)
return false;
return this.value.Equals(other);
}
Was it done on purpose or is it an omission?
Comment 1:
A brief comment to be clear. I suggested that Nullable<T> should have two Equals methods i.e.: public override bool Equals(object other) and public bool Equals(T other)
T
is not necessarilyIEquatable<T>
public bool Equals(T? other)
method? Otherwise, given declarationsdecimal? d1, d2;
,d1.Equals(d2)
would be invalid.Equal(object)
overload. But a generic Equals doesn't make sense unless you also have one onT
.T
is implicitly convertible toT?
, so would still be callable without a specific overload forT
. And without an overload forT?
, callingdecimal?.Equals
with an argument ofint?
would still have the same problem this question asks about, as it would resolve todecimal?.Equals(object)
and not convert the containedint
value to typedecimal
.