Description
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#-var-pattern- states the following:
A pattern match with the var pattern always succeeds for non-null expressions; if expr is null, the is expression is false. The non-null value of expr is always assigned to a local variable the same type as the runtime time type of expr. Its syntax is:
expr is var varnameThe following example uses the var pattern to assign an expression to a variable named obj. It then displays the value and the type of obj.
It then provides an example, of which the key component is the following:
object[] items = { new Book("The Tempest"), new Person("John") };
foreach (var item in items) {
if (item is var obj)
Console.WriteLine($"Type: {obj.GetType().Name}, Value: {obj}");
}
This very clearly and unambiguously indicates that item is var obj
will return false
if item
is null. This assertion is incorrect, and there are multiple references, including on https://github.com/dotnet/csharplang, stating that is var
will always return true, regardless of nullability.
This error seems to be the cause of some confusion:
- https://stackoverflow.com/questions/45844586/usage-of-var-pattern-in-c-sharp-7/55646164
- Is-expressions w/ patterns: Why
is var
allows nulls through? csharplang#981
There was a proposal to add this behavior, but it was declined: dotnet/csharplang#792
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 3126aaa9-8f5f-04f3-2d75-96477b6273cd
- Version Independent ID: 3f4b3eac-11eb-2dd6-4f27-b24537367288
- Content: is - C# Reference
- Content Source: docs/csharp/language-reference/keywords/is.md
- Product: dotnet-csharp
- GitHub Login: @BillWagner
- Microsoft Alias: wiwagn