Runtime: Prefer Nullable<T>.GetValueOrDefault() over manual checking

Created on 19 Mar 2020  路  5Comments  路  Source: dotnet/runtime

After checking a Nullable<T>.HasValue, it's common to see calls to Nullable<T>.Value; instead of calling Value, it's less work to call GetValueOrDefault(), as Value repeats the HasValue check. It's possible a future JIT could optimize away the duplicate check, but if nothing else using GetValueOrDefault() makes the job of the JIT easier.

Category: Performance

api-suggestion area-System.Runtime code-analyzer code-fixer

All 5 comments

Estimates:

  • Analyzer: Medium
  • Fixer: Medium

This is a high-noise analyzer. GetValueOrDefault is preferable from a performance standpoint, but this does not matter for 99% of the code.

From a style perspective, Value is preferable because semantically is more correct than GetValueOrDefault. You never want a default. If anything, you want the explicit assertion in Value.

If many high-noise analyzers like this one are default-on then people will learn that the analyzer suite is not meaningful to their work.

If many high-noise analyzers like this one are default-on then people will learn that the analyzer suite is not meaningful to their work.

It wouldn't be on by default.

There is an existing code quality issue for Nullable<T>.Value following Nullable<T>.HasValue (#13699).

What about correlation with IDE0030: UseCoalesceExpressionForNullable?
The rule suggest x ?? y instead of x != null ? x : y when x and y are nullable _value_ types or nullable _reference_ types.
For the new analyzer I'd prefer x.GetValueOrDefault(y) for value types - this clearly indicates that the type is value, which adds readability to the code. In the case IDE0030 should be changed to work only for reference types.

Was this page helpful?
0 / 5 - 0 ratings