Home » Dev Thinking » Using Using Again and Again

Using Using Again and Again

Here’s a quick little tip that addresses a minor thing that annoys me much more than it probably warrants…

If I need multiple instances of an variable of a given type – say, of a FileStream – with different initializing values, I often end up declaring repeated variable names:

FileStream fs1 = new FileStream("FirstFile.txt",File.Open);
FileStream fs2 = new FileStream("SecondFile.txt",File.Open);

A recent real-world example is when I was working with SQL command objects; I needed to execute one command, then check the results and either run a different command if it updated any records or just return (the source includes way to much extraneous code to share for this example, but you get the idea…)

Using repeating variable names isn’t the most terrible thing in the world, but I’ve spent many wasted minutes agonizing on *just* the right names for my variables, often ending up with something bogus like “firstFile / secondFile” or “readingFile / writingFile” – accurate, but really overkill for the amount of anxiety it causes and value achieved.

Recently I realized that I have another solution, at least some of the time. If my variable type is an object that supports the Using keyword, I can simplify my cleanup/reset code, while also eliminating the redundant variable declarations at the same time! Using example code is often written like this:

using (FileStream fs = new FileStream("FirstFile.txt", FileMode.Open))
{...}

and so I’ve used this for years and never really thought about alternate ways of writing that block. But it turns out that I don’t *have* to declare the variable type inside my using statement. I can solve my redundant variable name peeve with this simple tweak:

FileStream fs;
using (fs = new FileStream("FirstFile.txt", FileMode.Open))
{...}

using (fs = new FileStream("SecondFile.txt", FileMode.Open))
{...}

There is a caveat to this, namely that if you need access to the variables at the same time in your code (say, if you’re coping from one FileStream directly to another), you may still need separate variables. But it’s nice to know this works.


Leave a comment

Your email address will not be published.