Releasing Resource & The Syntax Candy

In C# practice, we may need to read or retrieve information from a text file; such as .text, .pdf and etc.

It is a good practice of critical thinking in this scenario, what if other objects or classes need to read this file?
The solution can be simple, and we can close the file or source after we use it, and other objects or class can use it after us. It is a common pattern in C# language, and I also believe this will benefit us when we work on a project with other programmers.


Case Study

We are writing a code snippet which will read a text file from our drive and other objects need to read it after us. So, we need to close it after we read it.


Talk Is Cheap, Show Me The Code


Another Approach

The code above does the work very well; however, it is a bit lengthy. Thanks for C#’s Syntax Candy. Syntax Candy does work for us behind the scene in C#, which saves us a lot of effort when we need to write a relatively large project.

In the above example, we use the keyword using as a syntax candy to rewrite the first code snippet. In the end, the file will be closed automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *