Skip to content

Proposal: change 'is var x' to check require non-null x #792

@sharwell

Description

@sharwell

In most cases where var is allowed for inferring a type, the resulting inferred type is syntactically interchangeable. One exception is the following:

public void Method(object input)
{
  if (input is object value)
  {
    // value has the static type 'object'
    // this block executes only if input is non-null
  }

  if (input is var value)
  {
    // value has the static type 'object'
    // this block executes even if input is null
  }
}

This behavior has several problems:

  1. Aside from the obvious is null, is var is the only cases where an is operator can produce a true result when the left hand side is null. This is confusing.

  2. The pattern-matching is operator has the potential to support null checks on exposed values in concurrent code (Discussion on non-null reference types #788 (comment)), but usage in this case would require the type name always be explicitly specified.

  3. If this is not changed, then after the language supports nullable reference types we will have a case where var cannot be replaced with the inferred type without a syntax error:

    string? local = ...;
    if (local is string a) { }
    if (local is var b) { } // b has the type 'string?'
    if (local is string? b) { } // syntax error, presumably equivalent to CS8116

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions