C# Language Proposal: defer Statement #9569
Replies: 1 comment 2 replies
-
See: #513 |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Introduce a
defer
statement to the C# language that schedules code for execution at the end of the current lexical scope, providing a cleaner and more intuitive pattern for resource cleanup and deferred actions.Motivation
Resource management is a frequent task in C# programming, especially in systems interacting with files, network streams, or databases. While C# provides the
using
statement andtry-finally
blocks, these constructs can become verbose and reduce readability, especially when multiple cleanup actions are needed.A
defer
statement offers:This pattern is popular in other languages like Go and can improve C# ergonomics, particularly for low-level programming tasks and infrastructure code.
Examples
Deferred actions execute in reverse order:
Detailed Design
Syntax
Where
statement
is any valid expression or block. Thedefer
statement is evaluated immediately, but its execution is delayed until the scope ends.Semantics
defer
must appear within a method body, local function, lambda, or anonymous method.Scope and Lifetime
defer
operates at the lexical scope level.defer
statement.Alternatives Considered
using
andtry-finally
: Functional but verbose and less composable.using var
declarations: Limited toIDisposable
, unsuitable for arbitrary cleanup logic.Drawbacks
Compatibility
defer
keyword does not currently exist in C#, making it a safe addition.Future Directions
defer
withawait
(e.g.,defer await conn.CloseAsync();
).Allow
defer
blocks:Integration with code analyzers for misuse detection.
Implementation Notes
A prototype implementation would involve:
defer
as a contextual keyword.Conclusion
Adding a
defer
statement to C# would significantly enhance its expressiveness and safety for resource management. It builds on a proven pattern from other languages while aligning with C#’s goal of being both powerful and readable.Beta Was this translation helpful? Give feedback.
All reactions