Allow using statement in out variable declaration #3024
Replies: 8 comments 2 replies
-
This isn't quite as short as what you propose, but you can use an already-existing variable as the subject of a
That is assuming, of course, that if |
Beta Was this translation helpful? Give feedback.
-
The problem with that is if TryOpenReader doesn't return true, reader is not disposed of. In the real world, reader would most likely be null in this case, but it'll still trigger warnings |
Beta Was this translation helpful? Give feedback.
-
I think this idea (or one similar to it) has been discussed elsewhere, but I can't find a reference. The effective scope is unclear - would The advantage of a distinct using declaration is that it's not participating in the creation of a nested scope, so it's clear that disposal will happen at the end of the enclosing block. |
Beta Was this translation helpful? Give feedback.
-
The same scoping rules which currently apply simply continues to apply. This is valid code which demonstrates the scope of result is not limited to the if block
and thus
I think the scope of a variable declared in an if statement is another topic and that ship has already sailed. If one wishes to limit the scope of the 'result' one could do the following.
|
Beta Was this translation helpful? Give feedback.
-
I think it's this one: #2894 |
Beta Was this translation helpful? Give feedback.
-
This also works: if (this.TryOpenReader(sourceName, out var reader)) using (reader)
{
} |
Beta Was this translation helpful? Give feedback.
-
The problem is this messes up auto formatters for me |
Beta Was this translation helpful? Give feedback.
-
Methods with IDisposable out parameters are really common in the macios bindings since almost all classes there are dispoable. This includes basically anything that returns an error (like Allowing a using statement/keyword for in-line variable declarations would make code for iOS/MacCatalyst much more elegant IMHO. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
C# 8.0 introduced the using declaration, which is convenient but cannot be used with out parameters. This leads to the awkward code below.
This could be simplified if the following code was valid
Beta Was this translation helpful? Give feedback.
All reactions