Home Pattern matching eliminated an extra variable
Post
Cancel

Pattern matching eliminated an extra variable

I was working on some code and was annoyed by the amount of code needed to repeatedly fetch an item. My code looked like:

1
2
3
4
5
6
7
8
9
10
SqlScript? nextVersion = null;
do
{
    nextVersion = await source.NextVersionAsync(latestVersion);
    if (nextVersion is not null)
    {
        await ExecuteScriptAsync(nextVersion);
        latestVersion++;
    }
} while (nextVersion is not null);

Basically, as long as a newer version exists, the loop continues. It felt like too much code, and I especially disliked declaring a variable up front and setting it to null.

I asked my Copilot pair programmer whether this could be improved, and it suggested the following replacement:

1
2
3
4
5
while (await source.NextVersionAsync(latestVersion) is { } nextVersion)
{
    await ExecuteScriptAsync(nextVersion);
    latestVersion++;
}

It explained that { } is a property pattern that matches any non-null object.

Cool! I had seen property patterns before, but I hadn’t realised they could be used this way.

This post is licensed under CC BY 4.0 by the author.