Can someone explain why result1 is false and result2 is true? code is given 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;
}
}
}
Because System.Decimal exposes an overload of Equals that can accept a Decimal value, and your second case is invoking that method (having converted the int parameter to a decimal using an implicit conversion) and returning true.
Whereas in the first case, the Nullable is trying its best, but can only invoke Object.Equals which will fail when comparing between an int and a decimal. If your first call was:
bool result1 = objOrder.PriceNullable.Equals(0M);
You'd be comparing two decimals, and it will now return true.
The Nullable generic Equals method can invoke neither the implicit conversion from int to decimal, nor the overload of equals that accepts a decimal value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With