C# "using" keyword
Tags: csharp, tutorial, beginners, programming
Published: 2022-05-05 21:48:49

In today's tutorial, we are going to discuss one of the keywords we frequently need to use: the _using_ keyword!

Let's get straight to it!

The **_using_** keyword can be used in two contexts:

1. As namespace directive
2. In _using_ statement blocks

## 1. Namespace directive 

There are three ways in which we can use _using_ here:

1. Make use of namespaces (traditional usage)
2. Make aliases for namespaces
3. Use static methods from classes namespaces

Down below I will explain each one of them, with a simple example involving writing a message to the console.

### 1.1. Make use of namespaces (traditional usage)

As we know, to write a message to the console we must use our friend _Console.WriteLine_.
We have two ways of calling _Console.WriteLine_. The first one is by calling the fully qualified name, which in this case would be _System.Console.WriteLine_. The second one would be using the _using_ keyword. The problem with the first approach is that, whenever we want to _Console.WriteLine_, we must prepend with _System_. Doing this once is fine, but imagine having to do so multiple times. Even further, imagine if we had a bigger namespace, say _Amazing.Big.Complex.DomainNamespace_, which would be needed to call every time we wanted to call a method. This would degrade very much the readability of our code.

In the following figure, you can see an example of this using statement, as well as the other "not so good" use case mentioned.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f86s2qmaqwdpg5f1jzl.png)

### 1.2. Make aliases for namespaces

Creating aliases for namespaces, at a visual glance, seems like creating a variable. In order to better explain this concept, please refer to the below image.


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/688llhmqk4yx46rjlz63.png)

As you can see in the first line, we create kinda a variable to store an alias for a specific namespace. In this case, it would not be worth it to make it, but with a bigger codebase, it could make sense in order to organize and make things look easier to read. Beware that this is not a widely used practice!

After declaring the alias we use it in the method _WriteMessageToConsoleWithAlias_.

### 1.3. Use static methods from classes namespaces

In this example, the WriteLine method is a static method from a static class (_Console_ class). Every time we want to execute the _WriteLine_ method, we must call _Console_ first. We can improve that by using the static class in the namespace. The following figure shows how to do so.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jhasdmeolhe921hllr1.png)

As you can see from the first line, we have inserted the _static_ keyword and also added the _Console_ class to the namespace. This will allow us to use the static methods inside the _Console_ class in our code without always needing to write _Console.WriteLine_. You can see this inside the _WriteMessageToConsoleWithStaticMethod_, where we call the _WriteLine_ method without needing to prepend the _Console_ class.

## 2. _using_ statement blocks

The using block statements are used when we want to create and manage object resources in a specific scope. When the scope ends, those resources are freed. Using the using block is important because there are types of objects that the Garbage Collector cannot clear, so we need to release such objects explicitly. Examples of such objects are file streams or database connections. Please refer to [this](https://www.codingame.com/playgrounds/6179/garbage-collection-and-c) article for more information on this topic.

If that might seem confusing, let's have a look at this simple, but clarifying, coding example, which writes a specific content to a file.

```
public void WriteToFile(string fileName, string content){
     using (StreamWriter writer = new StreamWriter(filename))
     {
          writer.WriteLine(content);
     } //after this, resources used are freed
}
```

The important aspect to notice here is that the objects we use in the parenthesis of the _using_ statement must implement the IDisposible interface. This interface contains the _Dispose_ method that will be called whenever the scope of the _using_ block ends. This _Dispose_ method objective should be cleaning the object mentioned before.

If we don't do what we mentioned before, and simply wrote two WriteLine methods from two StreamWriter, we would get an error (similar to the one you see in the figure down below).
That error occurs because the resources (from which _file1.txt_ is one of them) that are used are not freed up like they are when we use them inside the using block.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy92y2w5vy6rpzmsng7t.png)

But if, instead, you use the _using_ blocks, you don't have this error, due to the freeing of the resources. The following image shows just that.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fye9cb18m8s9wxz1ka51.png)

😁 **I hope this has helped!**

That's everything for now! Thank you so much for reading.

The source code for this tutorial can be found [here](https://github.com/RafaelJCamara/CSharpUsingKeyword).

If you have any questions please feel free to drop them off. 
Follow me if you want to read more about these kinds of topics!

**Social Media Links**:
[LinkedIn](https://www.linkedin.com/in/rafaelcamara96/)
[Twitter](https://twitter.com/RafaJCamara)
[Github](https://github.com/RafaelJCamara)