Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using on object vs not using it on object c#

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading