Defer keyword #9110
-
I’ve seen previous discussions about the defer keyword, but they mainly focused on its use for disposal scenarios. One comment even mentioned that they couldn’t find another practical use case. However, I recently encountered a case where defer would be particularly useful—when working with ArrayPool. Consider the following example: var bytes = ArrayPool<int>.Shared.Rent(1024);
defer ArrayPool<int>.Shared.Return(bytes);
// Use bytes until the end of the scope This approach improves readability by reducing nesting, similar to how C# has evolved with features like top-level statements and primary constructors. While defer in C# would just be syntactic sugar, it helps make resource management cleaner without adding significant complexity. I could easily see this being the preferred syntax for almost any occasion you find yourself reaching for a Of course, misuse could be a concern—just like accidentally using a Would love to hear people's thoughts on this. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Here's the existing discussion on a IMO, returning a leased resource falls under resource disposal. It's not difficult to create an adapter to |
Beta Was this translation helpful? Give feedback.
Here's the existing discussion on a
defer
statement: #513IMO, returning a leased resource falls under resource disposal. It's not difficult to create an adapter to
ArrayPool<T>
that would allow you to lease a buffer in ausing
block via extension method.SharpLab