Why is comparing decimal numbers with a zero value * with `0` different from comparing a decimal number with` 0`?

Can someone explain why result1 is false and result2 is true ? The code is below:

 namespace TestCsharp { class Program { static void Main(string[] args) { Order objOrder = new Order(0.0M); bool result1 = objOrder.PriceNullable.Equals(0);//returns false bool result2 = objOrder.PriceNullable.Value.Equals(0);// returns true } } public class Order { public decimal? PriceNullable { get; set; } public Order(decimal? priceNullable) { PriceNullable = priceNullable; } } } 
+7
source share
5 answers

Because System.Decimal calls the Equals overload, which can take the Decimal value, and your second case calls this method (converting the int parameter to Decimal using an implicit conversion ) and return true.

While in the first case, Nullable tries its best, but can only Object.Equals , which will fail when comparing between a int and a Decimal . If your first call was:

 bool result1 = objOrder.PriceNullable.Equals(0M); 

You would compare two Decimal s, and now it will return true .


The Nullable Equals Nullable method cannot refer to an implicit conversion from int to Decimal , or when overriding peers that take the Decimal value.

+4
source

The first check returns false because the passed value is not of decimal type. If you specify M with 0, you will get the truth.

 bool result1 = objOrder.PriceNullable.Equals(0M); 
+2
source

If we check the definition of Nullable<T>.Equals :

  /// <summary> /// Indicates whether the current <see cref="T:System.Nullable`1"/> object is equal /// to a specified object. /// </summary> ///... // true if the <paramref name="other"/> parameter is equal to the current // object; otherwise, false. public override bool Equals(object other); 

So you compared Nullable<decimal> and int . They are not equal.

+1
source

Nullable.Equals

In the first case, you are comparing an int object with a decimal object. if you have

 bool result1 = objOrder.PriceNullable.Equals(0.0M); 

result1 will be true.

+1
source

When you use

objOrder.PriceNullable.Equals(0) does it compare the decimal? object decimal? with the number 0 a decimal , which is False

But when you do

objOrder.PriceNullable.Value.Equals(0) it compares the decimal value equal to 0 and returns true

Do this to clarify

 decimal? nullableZero = 0; bool result3 = objOrder.PriceNullable.Equals(nullableZero);// returns true 
-one
source

All Articles