Note that there are some explanatory texts on larger screens.

plurals
  1. POBad practice? Non-canon usage of c#'s using statement
    text
    copied!<p>C# has the <code>using</code> statement, specifically for IDisposable objects. Presumably, any object specified in the <code>using</code> statement will hold some sort of resource that should be freed deterministically.</p> <p>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 <code>using</code> 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.</p> <p>What I have in mind is the sort of operation that frequently starts with a <code>BeginXXX()</code> and <code>EndXXX()</code> method, though there are plenty of different flavors, such as an asynchronous code execution that involves a "start" and a "join".</p> <p>Take this naive example.</p> <pre><code>webDataOperation.Start(); GetContentFromHardDrive(); webDataOperation.Join(); // Perform operation that requires data from both sources </code></pre> <p>What if, instead, the Start method returned an object whose <code>IDisposable.Dispose</code> method performs the join operation.</p> <pre><code>using(webDataOperation.Start()) { GetContentFromHardDrive(); } // Perform operation that requires data from both sources </code></pre> <p>Or, better yet, what I specifically had in mind: I have an object that does highly specialized graphics blitting and has a <code>Begin()</code> and <code>End()</code> method (a design also present in DirectX and XNA). Instead...</p> <pre><code>using(blitter.BlitOperation()) { // Do work } // Use result </code></pre> <p>It seems to be more natural and readable, but is it inadvisable, seeing as it uses the <code>IDisposable</code> interface and the <code>using</code> statement for unintended purposes? In other words, would this be on par with o<em>verloading an operator in a non-intuitive way</em>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload