The essential instruction in C# :using – Programming, Pseudocode Example, C# Programming Example
C# Collection

The essential instruction in C# :using

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:

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:

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:

This is equivalent to this code:

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.



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.