SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
781 stars 226 forks source link

Fix S1905 FP: Invalid warning about redundant cast with nullable reference types #9446

Closed bitbonk closed 3 months ago

bitbonk commented 3 months ago

Description

Sometimes it is required to explicitly cast from Foo to Foo? in a nullable reference context. For example to get rid of the CS8619 compiler warning.

In the below example, if we remove the (object?) cast that S1905 is complaining about, we get the following compiler warning:

// Demo.cs(10,42): Warning CS8619 : Nullability of reference types in value of type 'Dictionary<string, object>' doesn't match target type 'Dictionary<string, object?>'.

Repro steps

#nullable enable
using System:
using System.Linq;
using System.Collections.Generic;

static Dictionary<string, object?> BuildADictionaryWithNullableValues(IEnumerable<KeyValuePair<string, object>> existingNonNullValues)
{
    Dictionary<string, object?> result = existingValues.ToDictionary(e => e.Key, e => (object?)e.Value);

    result.Add("additionalNullableValue", null); // just to demo that it may make sense
    return result;
}

Expected behavior

The rule S1905 does not complain.

Actual behavior

The rule S1905 complains:

S1905: Remove this unnecessary cast to 'object'.

Related information

CristianAmbrosini commented 3 months ago

Hi @bitbonk,

I was not able to reproduce the issue using your snippet. It seems you are also using an outdated version of our analyzer. I would recommend updating to our latest version, 9.27.0.93347 (9.28 is likely to be released tomorrow). Anyway, the issue you are reporting looks very similar to #8413. A precondition needed to solve this specific issue was merged a few days ago. Feel free to check that issue to keep track of the progress.

Thanks!