SonarSource/sonar-dotnet

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

Closed this issue · 1 comments

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

  • SonarAnalyzer.CSharp 8.43.0.51858
  • Rider 2024.1
  • .NET 8
  • Windows 11

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!