-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C#7 pattern matching: if (obj is string s == false) does not work as expected. #17828
Comments
|
The unary negation operator It is by design. |
Hi @gafter, Correct me if I am wrong: When you say So: However, I am still getting confused about why this is not able to be compiled: void TestNotOK(object obj)
{
if (!(obj is string s == true)) return;
Debug.WriteLine(s);
} It seems like if we put an void TestNotOK(object obj)
{
if (obj is string s == true) Debug.WriteLine(s); // error
} Regards, |
If you have an expression for which a variable is "definitely assigned when true", then using static void Main()
{
bool b = true;
int x;
if (b && M(out x)) Console.WriteLine(x); // ok
if ((b && M(out x)) == true) Console.WriteLine(x); // error
}
private static bool M(out int x)
{
x = 1;
return true;
} |
Version Used:
C#7 with VS2017
Steps to Reproduce:
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:
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:And yes, if we are allowing user to compare with false, there would be some weird cases like
if (obj is string s != true)
orif (!(obj is string) == false)
. However, this is the users' problem.P.S.:
The following code cannot be compiled as well:
The text was updated successfully, but these errors were encountered: