-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
Version Used:
C#7 with VS2017
Steps to Reproduce:
- 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);
}- 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:
- It's ease to know if it is comparing to a constant false or not.
- 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);
}