Search code examples
c#nullablesyntactic-sugar

Rewrite HasValue to the ?? Operators


Is it safe to rewrite the following code:

bool b = foo.bar.HasValue ? foo.bar.Value : false;

to

bool b = foo.bar.Value ?? false;

where bar is the nullable type bool?


Solution

  • The easiest fix there is

    bool b = foo.bar.GetValueOrDefault();
    

    which is also actually cheaper than .Value as it omits the has-value check. It will default to default(T) , which is indeed false here (it just returns the value of the underlying T field, without any checks at all).

    If you need a different default to default(T), then:

    var value = yourNullable.GetValueOrDefault(yourPreferredValue);