Jessica
Jessica

Reputation: 2067

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

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?

Upvotes: 5

Views: 1364

Answers (2)

György Kőszeg
György Kőszeg

Reputation: 18013

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.

Upvotes: 1

Paulo Morgado
Paulo Morgado

Reputation: 14846

You're right!

ReSharper (not Visual Studio) is factually right, although I don't know why that would be a warning.

Although Customers is a collection of Customer, the use of SingleOrDefault hints that the value might be null which is not a Customer.

And nothing says that all values coming out of Customers are non-null.

Upvotes: 3

Related Questions