Search code examples
c#nullreferenceexceptionequals-operator

Any way how to force Equals to return false instead of Null reference exception?


I ran into a null reference exception on line:

dr["IsSandpit"] = p.MineralName.Equals("Sand");

Of course the fix is:

dr["IsSandpit"] = p.MineralName!=null && p.MineralName.Equals("Sand");

But I am wondering if a nullable type can be configured that the Equals method instead of throwing a null reference exception would just return false for a strongly typed variable? Or some method NotNullAndEquals?

Null in the database means something like "not filled" or empty and "empty" surely is not equal to "Sand". (Perhaps this is a duplicate but I have not found the right question)


Solution

  • You can call the static Equals method on both operands:

    var isEqual =  string.Equals("Sand", p.MineralName); // return false for null.
    

    This will remove the need to access a potentially null reference. Alternately, you can use the null propagation operator to avoid the operation if the value is null:

    var isEqual = p.MineralName?.Equals("Sand"); // return null for null.
    

    These are much better approaches, IMO, than using extension methods to hack together a method that can theoretically be called on a null reference, since that approach leads to confusion on whether you can safely call a method without checking for null. Imagine this code:

     if (!p.MineralName.Equals("Sand"))
     {  
           return p.MineralName.ToUpper(); // throws NullReferencException!
     }