Hello,
I would like to ask some help understanding the using
statement starting with C# 8.0
Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
For example from this:
public void MyFunction()
{
string manyLines = @"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
// -----------> 1
using (var reader = new StringReader(manyLines))
{
string? item;
do
{
item = reader.ReadLine();
Console.WriteLine(item);
} while (item != null);
}
// -----------> 2
// do some other long task...
// -----------> 3
}
to this:
public void MyFunction()
{
string manyLines = @"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";
// -----------> 1
using var reader = new StringReader(manyLines);
string? item;
do
{
item = reader.ReadLine();
Console.WriteLine(item);
} while (item != null);
// -----------> 2
// do some other long task...
// -----------> 3
}
- In the first scenario, the
reader
is disposed at the end of the using
block (-----------> 2), which means that after the closing bracket I can do more stuff but the resource has already been disposed.
- In the second scenario, I don't know what's happening. Is
reader
being disposed at the end of the function (-----------> 3)? Or is it disposed right after the last time that reader
is being used (-----------> 2)?
I read all the documentation but I am sorry I still don't understand for sure.
In my code, I would like to dispose my resource as soon as possible and I would like to know if switching to the new using
statement will keep the behavior the same.
Thanks!