The ‘using’ keyword

Joe pointed out that the C# PGP decryption code that I wrote could be better; specifically I should be checking the xExitCode property of the Process instance and the code would also be better served if I made certain that I disposed of the Process instance by calling the Close() method when I’m done using it. The ExitCode improvement is relatively simple to add; start the process, read any lines of output and then check the ExitCode to see if everything went smoothly:

Process process = Process.Start(psi);
...
while(!process.HasExited) {
... // do stuff
}
if (process.ExitCode != 0) {
// something went wrong..
}

The second thing that Joe mentioned was the ‘using’ statement, which is a novel feature of C# that provides “… an easy way for C# code to acquire and release unmanaged or otherwise precious resources.” The code I originally wrote didn’t destroy the handle to the process; after all was said and done I should have called the Close() or Dispose() method of the process:

Process process;
try {
process = Process.Start(psi);
...
} catch {
process.Close();
}

The ‘using’ statement is syntactic sugar that’s a shortcut for the well worn try / catch idiom and shortens the above example to:

using (Process process = Process.Start(psi)) {
... // do stuff w/ the process
}

which then automatically calls the Dispose() method of the process.

Joe goes on to hijack the ‘using’ statement in some other novel ways which should you check out when you have a chance.

One thought on “The ‘using’ keyword”

  1. try {
    process = Process.Start(psi);
    } catch {
    process.Close();
    }

    ..isnt the same as ‘using’ as in that try/catch snippet ‘close’ is only called when there occured an exception. What you might have ment is..

    try {
    process = Process.Start(psi);
    } catch {
    ..
    }
    finally {
    process.Close();
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>