-
Notifications
You must be signed in to change notification settings - Fork 4.1k
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
Out variable declaration with underscore as the name behaves inconsistently #18015
Comments
Is this by design?
The following code compiles _ = 2;
_ = "wat";
_ = GetSomething();
_ = new Something(); This looks meaningless, but C# 7 adds tupple, so it's possible to var (a, _, _) = GetSomeTuple();
(int, int, string) GetSomeTuple() => (0, 1, "wat"); |
Huh? Is var _ = "foo";
Console.WriteLine(_); This works in both C#6 and C#7. The following fails in C#6 though but compiles fine in C#7: _ = "asd"; // CS0103 on C#6
Console.WriteLine(_); That behavior would appear normal and desired to me. An underscore, while being a poor choice for a variable name, is still a valid variable name. And unless I declare that, it shouldn’t work. For the discarding functionality in out variables and for tuple destructuring, I would expect this to be a special syntax feature that does not actually do anything to a “real” name |
The first line works in C#7, the second doesn't, because you never declared a variable named It's the same as when The design notes from Nov 15 (#16674) mention what has been done to avoid errors for existing uses of |
Yes, |
For reference, here's the feature design doc: https://github.com/dotnet/roslyn/blob/master/docs/features/discards.md |
Triggered by this question on Stack Overflow, we noticed a few inconsistencies when using the new C#7 out variable declaration with an underscore as the variable name (the one used for the discard functionality).
As expected, the following code does not compile since the
_
makes the out variable be discarded:However, assigning to
_
works for some reason:Similarly, if you actually declare the underscore as an inline out variable, you get the same result, even though it should be a real variable now:
There seems to be something weird going on with the syntax parsing there, since the
_
is recognized as a discard regardless of whether it’s an actual discard or a variable declaration. And then the behavior to be able to assign something to_
is just odd; the name shouldn’t be available for anything, not even assigning to it.(I’ve tested this with the most current version of Visual Studio 2017 15.0.0+26228.9)
The text was updated successfully, but these errors were encountered: