Recently I saw such code in a .Net Core 6 project:
persons = persons.Where(c => c is { Id: { } }).ToArray()
I assumed it is "is" operator pattern in C# 9 and tried to understand how I can read it, but could not explain what it does with words.
Based on the assumptions on what the code is doing, I managed to write a test for it, so, it looks like it checks c for null and Id for null as well.
How I should approach reading such syntax?
The test for the logic (Xunit, FluentAssertion)
record TestPerson(int? Id, string Name);
[Fact]
public void TestStrangeSyntax()
{
var persons = new TestPerson[] { new TestPerson(1, "John"), null, new TestPerson(null, "Jane") };
persons = persons.Where(c => c is { Id: { } }).ToArray();
persons.Should().BeEquivalentTo(new [] { persons[0] });
}
Edit: I tried to change the code in Where
to
c => c != null && c.Id !=null
and my IDE suggested to convert it to the pattern. Since we both use the same IDE, I assume this was what the person did.
After I tried to change it to
c?.Id != null
no refactor was suggested.
Also, after reading the answers from @Panagiotis Kanavos and @Orace I agree it can be treated as a duplicate.