Skip to content

RCS1077: Replacing OfType<T>() with Where(x => x != null) might change the nullability of the returned collection #1016

@KernelLeak

Description

@KernelLeak

Product and Version Used: Roslynator 2022 4.2.0

Steps to Reproduce:

string?[] strings = { "Foo", "Bar", null };

foreach (var s in strings.OfType<string>())
{
    string t = s;
    Console.WriteLine(t);
}

Roslynator will recommend RCS1077 ("Call 'Where' instead of 'OfType'") in the foreach statement.

Since OfType returns string[], while the Where keeps the type of the enumeration as string?[], applying the fix will make the s in the assignment to t get the warning "'s' may be null here", which wasn't present before.

Actual Behavior:
Roslynator recommends the change without taking the nullability of s before and after the change into account.

Expected Behavior:
Roslynator only recommends the change if the return types of Where and OfType are identical, especially when taking nullability into account.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions