Getting warning "The source expression is always of pattern's type, matches on all non-null values"

Viewed 931

I am trying to use the new C# 7 pattern matching feature in this line of code

if (Customers.SingleOrDefault(x => x.Type == CustomerType.Company) is Customer customer)
{
    ...
}

But for some reason Resharper/Visual Studio 2017 is giving me a warning under is Customer with the following message

The source expression is always of pattern's type, matches on all non-null values

But customer can also be null right? Can anyone please explain to me why it's given this warning?

2 Answers

The warning goes away if you replace is Customer customer with is {} customer (requires C# 8).

JetBrains recommends this solution by the way, saying it has some advantages when you refactor the code.

But if you find the code more readable with exact types and you prefer letting the compiler fail when you change types (to force a review, for example) you can just disable the warning completely. Please note that the compiled code (both IL and JITted) will be the same in both cases.

Related