"Use recursive patterns" suggests redundant "this is { ... }" pattern
Version Used:
Microsoft Visual Studio Enterprise 2022 Version 17.2.4 VisualStudio.17.Release/17.2.4+32602.215
C# Tools 4.2.0-4.22281.5+8d3180e5f00d42f0f0295165f756f368f0cbfa44
Steps to Reproduce:
class Bar
{
public Qux? Qux { get; }
void Foo()
{
if (Qux != null && Qux.Color != ConsoleColor.Red)
{
Console.WriteLine("A");
}
}
}
class Qux
{
public ConsoleColor Color { get; }
}
Generated code in Foo is equivalent to:
if (Qux != null && Qux.Color != ConsoleColor.Red) { ... }
Expected Behavior:
"Use recursive patterns" rewrites Foo to:
void Foo()
{
if (Qux is { Color: not ConsoleColor.Red })
{
Console.WriteLine("A");
}
}
Generated code in Foo is equivalent to:
Qux qux = Qux;
if (qux != null && qux.Color != ConsoleColor.Red) { ... }
Actual Behavior:
"Use recursive patterns" rewrites Foo to:
void Foo()
{
if (this is { Qux: not null, Qux.Color: not ConsoleColor.Red })
{
Console.WriteLine("A");
}
}
where this is { ... } should always pass the null check, and simply using Qux is { Color: not ConsoleColor.Red } would already carry the null check for Qux.
Generated code has the redundant null check for this:
if (this != null)
{
Qux qux = Qux;
if (qux != null && qux.Color != ConsoleColor.Red)
{
Console.WriteLine("A");
}
}
@alrz ?
I think avoiding the redundant null check pattern will also resolve the issue with 'this', however we still do this when there's no other common receiver eg
this.Prop1 && this.Prop2
Hey, can I take this?
Definitely!