-
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
[Proposal] Variable declarations at yield return #3664
Comments
Compound assignment with a control statement is anything but obvious, but outside of terseness of code what is the benefit? |
OTOH, the variable may still be useful after |
Also I believe the Actually now that I think about it, the |
While I see how this saves a small amount of typing, I feel like this is really makes the code more difficult to read. Is there some benefit besides saving a few key strokes? |
Is there any reason why you wouldn't want to do that? I.e.: var temp = current + last;
yield return temp; |
Consider this scenario: public IEnumerable<string> HelloWorld()
{
yield return "Hello";
yield return "World";
} Say I want to add a bit of logging: public IEnumerable<string> HelloWorld()
{
var h = "Hello";
yield return h;
Console.WriteLine(h);
var w = "World";
yield return w;
Console.WriteLine(w);
} Now the strings are being created separately from the yield return. This proposal would allow: public IEnumerable<string> HelloWorld()
{
yield return var h = "Hello";
Console.WriteLine(h);
yield return var w = "World";
Console.WriteLine(w);
} This flow is more consistent with the original, where the strings are created at the site of the yield return. |
I've obviously used very simplistic code in these examples. Real world examples are much more complicated, so the solution has a bigger impact. |
@bondsbw Your scenario doesn't make much sense. You wouldn't be logging the yielded value until/unless the consumer attempted to move to the next value. You'd want to capture the result to a variable, log it, and then yield it, potentially with a helper method to do most of that. Beyond that I think that this conversation is and should be wrapped up with the proposal for declaration expressions as that is effectively what it is. |
@HaloFour It was just a very simplistic example. Nitpicking the usefulness of the parts of the code that aren't related to the proposal is not helpful. But I agree that declaration expressions would (should) provide this, so I'll close this issue. |
This proposal is to allow variable declarations at the site of
yield return
:The closest I can do right now is to define the variables before the
yield return
:The current syntax isn't as useful. I can't use
var
to declare the variables, so I might as well initialize them on the same line they are being declared.The text was updated successfully, but these errors were encountered: