-2

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);
TimBro
  • 1
  • 1
  • 1
    This one also may answer your question [Using declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations) – Reza Heidari Apr 05 '22 at 07:31

3 Answers3

1

using (thing) { ... } is just shorthand (approximately) for try { ... } finally { thing?.Dispose(); }, when referring to IDisposable.Dispose() (there's also an async twin). Most IDisposable types should be actively disposed to (for example) close files, release sockets, etc; for StringReader, it really won't matter (the dispose is a no-op), but: might as well do it anyway.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

I think you should check these two previous answers

What are the uses of "using" in C#?

use of "using" keyword 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 the Garbage Collector does not know exactly when it should release those resources. So the using keyword and block will dispose the object as soon as your execution flow gets out of the scope of the using block.

Check also these Microsoft documentation about Unmanaged Resources

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects

Cleptus
  • 3,446
  • 4
  • 28
  • 34
Douglas Ferreira
  • 434
  • 1
  • 7
  • 23
0

Because "stream" is unmanaged resources, if not used "using", unmanaged resources will always occupy memory.

"using" is a sugar, The IL Code is "Dispose" method that calls"Stream" object.

Of course, you can also call "Dispose" method without "using"; "reader.Dispose()"