A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope. For example, consider the following code that writes a text file:
static int WriteLinesToFile(IEnumerable<string> lines)
{
using var file = new System.IO.StreamWriter("WriteLines2.txt");
// Notice how we declare skippedLines after the using statement.
int skippedLines = 0;
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
else
{
skippedLines++;
}
}
// Notice how skippedLines is in scope here.
return skippedLines;
// file is disposed here
}
In the preceding example, the file is disposed when the closing brace for the method is reached. That's the end of the scope in which file is declared. The preceding code is equivalent to the following code that uses the classic using statement:
static int WriteLinesToFile(IEnumerable<string> lines)
{
// We must declare the variable outside of the using block
// so that it is in scope to be returned.
int skippedLines = 0;
using (var file = new System.IO.StreamWriter("WriteLines2.txt"))
{
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
else
{
skippedLines++;
}
}
} // file is disposed here
return skippedLines;
}
In the preceding example, the file is disposed when the closing brace associated with the using
statement is reached.
In both cases, the compiler generates the call to Dispose()
. The compiler generates an error if the expression in the using
statement isn't disposable.