Whats the difference and benifits of "using" in this case.
I will state two simular cases please explain why I should or shoudn’t use "using" before my reader in this case.
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.";
using var reader = new StringReader(manyLines);
string? item;
do
{
item = reader.ReadLine();
Console.WriteLine(item);
} while (item != null);
vs
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.";
var reader = new StringReader(manyLines);
string? item;
do
{
item = reader.ReadLine();
Console.WriteLine(item);
} while (item != null);
>Solution :
I think you should check these two previous answers
What are the uses of "using" in C#?
But being brief, it’s not a matter of "advantage" its more a need. There are object in .NET that have unmanaged resources (resources outside the CLR, like database connections, sockets, OS syscalls, OS APIs etc) and these resources must be disposed manually, because Garbage Collector don’t know exactly when use release these resources. So using keyword and block will dispose as soon as your execution flow get out of the scope of using block
Check also these Microsoft documentation about Unmanaged Resources
https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged
https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects