The using statement
Before we introduce the using
statement, let's see how explicit resource management is done in a proper manner. This will help you to better understand the need and workings of the using
statements.
The Car
class we looked at in the previous section can be used as follows:
Car car = null; try { car = new Car(new Engine()); // use the car here } finally { car?.Dispose(); }
A try-catch-finally
block (although catch
is not explicitly shown here) should be used in order to ensure proper disposal of the object when it is no longer needed. However, the C# language provides a convenient syntax for ensuring the correct disposal of an object with the using
statement. This has the following form:
using (ResourceType resource = expression) statement
The compiler transforms this into the following code:
{ ResourceType resource = expression; ...