New Rule: Avoid default with ternary conditional operator for nullables

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.

Hi,

I know this is obvious to you, but it’s not to me. What language is this? :sweat_smile:

 
Thx,
Ann

Sorry, I thought I tagged it for .NET (The example is C#), but me bad. I’m not sure if could be relevant for other languages.

1 Like

Hi Corniel!

That’s quite interesting, I think it could indeed be a new rule idea with the exception of default(T) and default(T?), as you have already noted.
I will assign this to our Product Manager for further evaluation and prioritization.

1 Like