简体   繁体   中英

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)

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!
 }

The expression

p.MineralName?.Equals("Sand")

will evaluate to null if p.MineralName is null. You can then coalesce it to false, like so:

p.MineralName?.Equals("Sand") ?? false

As an option you can utilize a self-created NotNullAndEquals extension method:

    public static class Utilities {
        public static bool NotNullAndEquals(this string value, string expected) {
            return value != null && value.Equals(expected);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM