Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 245
Jessica Avatar asked Aug 01 '17 05:08

Jessica


2 Answers

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.

like image 106
Paulo Morgado Avatar answered Oct 01 '22 03:10

Paulo Morgado


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.

like image 44
György Kőszeg Avatar answered Oct 01 '22 01:10

György Kőszeg