If we take a look at this code:
void Assign(bool condition)
{
decimal? value1 = condition ? 3.14m : default; // Noncompliant
^^^^^^^
decimal? value2 = condition ? Pi() : default; // Noncompliant
^^^^^^^
}
decimal? Pi() => 3.14m;
When condition
is false
, value1
will be 0
, and value2
will be null
. Although from a compiler perspective this perfectly logical, fallible human beings might expect (and hence miss) that in the first case, the value turns out to be 0
, instead of null
.
I would propose a rull that, when assigning nullable value types with a ternary conditional operator, the default keyword should be avoided:
void Assign(bool condition)
{
decimal? value1 = condition ? 3.14m : 0m;
decimal? value2 = condition ? Pi() : null;
}
decimal? Pi() => 3.14m;
You could argue that default(T)
and default(T?)
should be allowed though.