In this code snippet, we will take a look at the using keyword in C#.
The using keyword can be used as a directive to include a namespace or it can be used as a statement. Using it as a statement the using keyword ensures that the dispose() method gets called(even if an exception occurs).
When you are done using a resource the dispose() method needs to be called. It is implemented by most classes that work with IO resources such as files, network connections, … We can do what using does manually with the try catch block, but it’s not as elegant and compact.
Note: using doesn’t catch and can’t handle exceptions, it only ensures your resource is properly disposed of(even if an exception occurs). You must still use the try catch block to catch and handle exceptions.
Let’s have a look at the code below to see how to use the using keyword.