-
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
[Proposal] Allow for inline creation and handling of IDisposable objects (RAAI) #181
Comments
The big reason |
Something like this was mentioned on CodePlex where it would be syntactic candy for public void Method(int x) {
using var disposable1 = new SomeDisposable();
if (x == 0) {
using var disposable2 = new SomeOtherDisposable();
// do stuff
} // disposable2 automatically disposed here
// do other stuff
} // disposable1 automatically disposed here
// equivalent to
public void Method(int x) {
using (SomeDisposable disposable1 = new SomeDisposable()) {
if (x == 0) {
using (SomeOtherDisposable disposable2 = new SomeOtherDisposable()) {
// do stuff
}
}
// do other stuff
}
} The same rules would have to apply in that the declared variable would be effectively read only. |
@RichiCoder1 Scoping rules should apply, similar to the stack objects in C++. This would effectively give you deterministic destruction. |
@RichiCoder1 The one advantage I think is that this would apply to the wide variety of existing |
@HaloFour as mentioned in the other thread, |
@RichiCoder1 Maybe, but since the framework is absolutely loaded with existing |
Hmm. I disagree with trying to fit an |
This syntax sugar would be very useful for cleaning up nested usings, but it would be too confusing to have both this and a destructible. I believe a merger of the ideas (as I suggested in #161) would be phenomenal. |
@RichiCoder1 Well, I think that In C++ 'destructible' objects are not created via new, they are created simply by declaring the variable. The proposed syntactic sugar is:
|
If I'm reading the proposal right, structs would largely behave the exact same way. It's classes where the difference would exist. Edit: Though C# wouldn't have the ability to do
The risk of doing this is diluting |
|
I'm not sure I understand how the syntax is bad. The point of Put another way, think in terms of The Pit of Success. |
Hmm, I think you are right. Let me take another look at destructibles then. |
I like the syntax from #5881 better. |
@gafter 👍 Another, potential option for RAII style "things" is to add destructors to |
We like this idea, but we think we prefer the syntax in #5881. So closing this one as a dup. |
Proposed syntax would be
The code is just a shorter way of writing:
Which is actually much more composable with
try-catch
pattern. Now we can remove one extra pair of curly braces and write:The text was updated successfully, but these errors were encountered: