Skip to content

Incorrect description of is var behavior #11804

Closed
@Zenexer

Description

@Zenexer

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 varname

The 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:

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.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions