C# Using Block

The using block provides proper declaration and dispose of objects that implement IDisposable interface. IDisposable is implemented by managed classes that access unmanaged resources. FileStream is one such classes that accesses IntPtr and SafeFileHandle which are unmanaged handles.

Finally Block

The problem with unmanaged resources is that they can throw exceptions which are beyond the control of the programmer.

For example a FileNotFoundException is thrown if the file being access by a FileStream does not exist. These exceptions need to be handled by the code by defining try catch blocks. And in the end a finally block needs to be defined for closing and disposing the FileStream.

FileStream file = null; try { file = new FileStream("C:\\myFile.txt", FileMode.Open); // Read the file } catch { throw; // Handle the exception or throw it } finally { if (file != null) { file.Close(); file.Dispose(); } }

The Close() method is called for temporarily closes the resource used by the object they can be reopened again; whereas Dispose() completely releases all the resources.
Using Block

In the above code if you notice in the finally block the file is first checked if it is null only then close() and dispose() can be called. The reason is that if an exception occurs even before instantiating the file object then it will throw an exception again in the finally block when we try to close it.

To avoid these handling issues and have a more cleaner code we use the using block as shown below.

try { using (FileStream file = new FileStream("C:\\myFile.txt", FileMode.Open)) { // Read the file } } catch { throw; // Handle the exception or throw it }

Note that the scope of file object is limited to the braces only { … } and not beyond that.
Tags:
Hot on Web:


About author