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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With