Reputation: 8104
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)
Upvotes: 3
Views: 526
Reputation: 14700
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!
}
Upvotes: 5
Reputation: 990
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);
}
}
Upvotes: -1
Reputation: 52270
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
Upvotes: 0