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.Decimalexposes an overload ofEqualsthat can accept aDecimalvalue, and your second case is invoking that method (having converted theintparameter to adecimalusing an implicit conversion) and returning true.Whereas in the first case, the
Nullableis trying its best, but can only invokeObject.Equalswhich will fail when comparing between anintand adecimal. If your first call was:You’d be comparing two
decimals, and it will now returntrue.The
NullablegenericEqualsmethod can invoke neither the implicit conversion frominttodecimal, nor the overload of equals that accepts adecimalvalue.