C# has the using
statement, specifically for IDisposable objects. Presumably, any object specified in the using
statement will hold some sort of resource that should be freed deterministically.
However, it seems to me that there are many designs in programming which have a single, definite beginning and end, but lack intrinsic language support. The using
construct provides an opportunity to use the built in features of a code editor to, at least, clearly and naturally highlight the scope of such a design or operation.
What I have in mind is the sort of operation that frequently starts with a BeginXXX()
and EndXXX()
method, though there are plenty of different flavors, such as an asynchronous code execution that involves a "start" and a "join".
Take this naive example.
webDataOperation.Start();
GetContentFromHardDrive();
webDataOperation.Join();
// Perform operation that requires data from both sources
What if, instead, the Start method returned an object whose IDisposable.Dispose
method performs the join operation.
using(webDataOperation.Start()) {
GetContentFromHardDrive();
}
// Perform operation that requires data from both sources
Or, better yet, what I specifically had in mind: I have an object that does highly specialized graphics blitting and has a Begin()
and End()
method (a design also present in DirectX and XNA). Instead...
using(blitter.BlitOperation()) {
// Do work
}
// Use result
It seems to be more natural and readable, but is it inadvisable, seeing as it uses the IDisposable
interface and the using
statement for unintended purposes? In other words, would this be on par with o*verloading an operator in a non-intuitive way*?