roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

IDE0004: Cast is redundant not true when removing nullable for returning a value.

Open cafenroy opened this issue 6 years ago • 1 comments

Analyzer

Diagnostic ID: https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0004: Remove unnecessary cast

Analyzer source

SDK: Built-in CA analyzers in .NET 5 SDK or later

Version: SDK 5.0.100

Describe the bug

With the <Nullable>enable</Nullable> parameter ON, a cast to a non-nullable might be necessary.

The analyzer proposes to remove an unnecessary cast from this code.

static IEnumerable<string> DoThis(IEnumerable<string?> notreallynull)
{
    return notreallynull.Where(s => s is not null) as IEnumerable<string>;
}

Expected behavior

The analyzer should not say unnecessary in that situation.

cafenroy avatar Nov 27 '20 15:11 cafenroy

I can reproduce the issue.

Note that if you use the following syntax:

static IEnumerable<string> DoThis(IEnumerable<string?> notreallynull)
{
	return notreallynull.OfType<string>();
}

You achieve the same result and you don't have FP.

Evangelink avatar Dec 01 '20 13:12 Evangelink