roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

"Use recursive patterns" suggests redundant "this is { ... }" pattern

Open bartdesmet opened this issue 3 years ago • 2 comments

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");
		}
	}

bartdesmet avatar Sep 17 '22 20:09 bartdesmet

@alrz ?

CyrusNajmabadi avatar Sep 17 '22 21:09 CyrusNajmabadi

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

alrz avatar Sep 20 '22 19:09 alrz

Hey, can I take this?

ghost avatar Feb 19 '24 20:02 ghost

Definitely!

CyrusNajmabadi avatar Feb 19 '24 20:02 CyrusNajmabadi