Skip to content

C#7 pattern matching: if (obj is string s == false) does not work as expected. #17828

@sumtec

Description

@sumtec

Version Used:
C#7 with VS2017

Steps to Reproduce:

  1. Create a new C#7 project and add the following function to any ".cs" file:
void Test(object obj)
{
  if (obj is string s == false) return;
  Debug.WriteLine(s);
}
  1. Observe the IntelliSense or Build output.

Expected Behavior:
No error; Or,
Showing an error saying something like "Pattern matching in the if statement is not allow to test with false" on the line of the "if" statement.

Actual Behavior:
Showing an error saying "Use of unassigned local variable 's'" on the line of the statement "Debug.WriteLine(s)".

Reason for thinking this is a bug:
The following code can be compiled without issue:

void TestOK(object obj)
{
  if (!(obj is string s)) return;
  Debug.WriteLine(s);
}

The !x is equivalent to 'x == false'. And '!' is sometimes easy to be skipped by human eyes.

And I understand that in the example of if (obj is string s == nonConstantValue) ..., we don't know if obj is a string or not if the "if-block". So, the "s" is meaningless. However, I think:

  1. It's ease to know if it is comparing to a constant false or not.
  2. We should, in this example, tell the user that the s here is meaningless and not allow them to write such an "if" statement, instead of showing "unassigned s" when the user attempt to use it.

And yes, if we are allowing user to compare with false, there would be some weird cases like if (obj is string s != true) or if (!(obj is string) == false). However, this is the users' problem.

P.S.:
The following code cannot be compiled as well:

void TestTrue(object obj)
{
   if ((obj is string s) == true) Debug.WriteLine(s);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions