Clean code with using keyword in C#

Amr elshaer
3 min readDec 24, 2021

--

In this article, we do not discuss how to use Using the keyword in c#,but we will discuss how to benefit from using keywords to improve our code.

The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection

the using statement does the calls Dispose() method automatically to make the code cleaner and more elegant. Within the using block

this code will convert to try — finally in IL (Intermediate Language) compiler like this.

Now let’s dive into our example to benefit from using, in our example I want to measure the time that operation takes, I know a lot of ways can use to implement this put, I want a simple example to demonstrate our goal.

GetChatRoom is a method to return ChatRoom and Stopwatch to measure the time of our code.

but if I want to measure another method we will write this code again and again for every time we want to measure our operation execution time.

but now we break our principle DRY(Don’t repeat yourself)

let’s improve our code

first, we create a class that implements IDispoable and add our code that executes after our code.

let’s replace try-finally with using

If you want to measure any operation you can use this code

--

--