Use GetValueOrDefault() over Value when Nullable<T> known non-null
GetValueOrDefault() is an easily-inlined access to a field as this will hold the correct value for both HasValue and !HasValue cases. The Value property in comparison contains a branch on a check that the Nullable<T> has its internal hasValue flag to decide whether to throw InvalidOperationException or not. Hence when a nullable type is known to have a value (not be null) and one wants the value, rather than to possibly trigger the exception-throw GetValueOrDefault() has a slight performance benefit over Value. Accordingly, replace calls to the Value property with calls to GetValueOrDefault() when previous checks or assignments guarantee the value is not null.
This commit is contained in:
@@ -138,7 +138,7 @@ namespace Newtonsoft.Json.Utilities
|
||||
return val1;
|
||||
}
|
||||
|
||||
return Math.Min(val1.Value, val2.Value);
|
||||
return Math.Min(val1.GetValueOrDefault(), val2.GetValueOrDefault());
|
||||
}
|
||||
|
||||
public static int? Max(int? val1, int? val2)
|
||||
@@ -152,7 +152,7 @@ namespace Newtonsoft.Json.Utilities
|
||||
return val1;
|
||||
}
|
||||
|
||||
return Math.Max(val1.Value, val2.Value);
|
||||
return Math.Max(val1.GetValueOrDefault(), val2.GetValueOrDefault());
|
||||
}
|
||||
|
||||
public static double? Max(double? val1, double? val2)
|
||||
@@ -166,7 +166,7 @@ namespace Newtonsoft.Json.Utilities
|
||||
return val1;
|
||||
}
|
||||
|
||||
return Math.Max(val1.Value, val2.Value);
|
||||
return Math.Max(val1.GetValueOrDefault(), val2.GetValueOrDefault());
|
||||
}
|
||||
|
||||
public static bool ApproxEquals(double d1, double d2)
|
||||
|
||||
Reference in New Issue
Block a user