Today, I present you a very particular instruction introduced in the language C # (since V1).
I really like this instruction because it allows to make clean and efficient code. This is indeed the using statement in C #.
Using is first used to import references from namespaces (using directive).
Using is also used as an instruction in a block of code and what we are going to see now.
For those who have already worked with system resources, socket connections, databases, you know that you must always close these resources at the end of your treatment or in case of error.
This type of pattern of development always introduces redundant code: a treatment to do at the end “normal” and a treatment in case of error.
The C # language introduces the try … finally statements that make it possible to manage this type of mechanism.
For example:
1 2 3 4 5 6 7 8 9 10 11 |
StreamReader reader = new StreamReader("MonFichier.txt"); try { s = reader.ReadLine(); } finally { reader.Close(); } |
You will notice that this code is already not bad in terms of clarity (compared to the C I mean).
Nevertheless, the C# language allows you to go further with the IDisposable pattern and the using statement.
With the example below (equivalent), you will understand immediately:
1 2 3 4 5 6 7 |
using (StreamReader reader = new StreamReader ("MyFile.txt")) { s = reader.ReadLine (); } // Here at the end of the block, the compiler makes an automatic call to reader.Dispose (). |
The using statement must be used with a class that implements IDisposable (contains a Dispose () method). At the end of the code block, the compiler generates a call to the Dispose method of this object.
In our case, StreamReader encloses the file and thus releases the resources. Interesting no?
I like to talk about this instruction because I find it nice to use (impossible to forget the close), it is possible to make a return anywhere, which generally allows to simplify the code in the end (in terms of readability).
The using statement can be used with multiple objects and nested.
For example:
1 2 3 4 5 6 7 8 9 |
using (StreamReader reader = new StreamReader ("MyFile.txt")) { using (StreamWriter writer = new StreamWriter ("MyOut.txt")) { // treatment... }} } |
This is equivalent to this code:
1 2 3 4 5 6 |
using (StreamReader reader = new StreamReader ("MyFile.txt"), StreamWriter writer = new StreamWriter ("MyOutput.txt")) { } |
I leave you now practice for yourself. I strongly urge you to use this instruction. After several uses you will not be able to do without it.
Feel free to leave your comments on the different ways to use the using statement.