Abuse using and Dispose() for scope handling of not to be released objects?
anti-patterns, c#, using
Solution
This is not an abuse at all - that is a common scope-handling idiom of C#. For example, ADO.NET objects (connections, statements, query results) are commonly enclosed in `using` blocks, even though some of these objects get released back to their pools inside their `Dispose` methods:
using (var conn = new SqlConnection(dbConnectionString)) {
// conn is visible inside this scope
...
} // conn gets released back to its connection pool
Problem
For convenience and safety reasons i'd like to use the `using` statement for allocation and release of objects from/to a pool ``` public class Resource : IDisposable { public void Dispose() { ResourcePool.ReleaseResource(this); } } public class ResourcePool { static Stack<Resource> pool = new Stack<Resource>(); public static Resource GetResource() { return pool.Pop(); } public static void ReleaseResource(Resource r) { pool.Push(r); } } ``` and the access the pool like ``` using (Resource r = ResourcePool.GetResource()) { r.DoSomething(); } ``` I found some topics on abusing `using` and `Dispose()` for scope handling but all of them incorporate `using (Blah b = _NEW_ Blah())`. Here the objects are not to be freed after leaving the using scope but kept in the pool. If the using statement simply expands to a plain `try finally Dispose()` this should work fine but is there something more happening behind the scenes or a chance this won't work in future .Net versions?