Simplified Disposal and Compressed Streams
Learn about the “using” statement for automatic resource management and how to compress XML data using GZip and Brotli algorithms.
We'll cover the following
We can simplify the code that needs to check for a null object and then call its Dispose
method by using the using
statement. Generally, we would recommend using
using rather than manually calling Dispose
is recommended unless we need greater control.
The using
keyword
Confusingly, there are two uses for the using
keyword:
Importing a namespace.
Generating a
finally
statement that callsDispose
on an object that implementsIDisposable
.
The compiler changes a using
statement block into a try-finally
statement without a catch statement. We can use nested try statements, so if we do want to catch any exceptions, we can, as shown in the following code example:
Get hands-on with 1400+ tech skills courses.