C# Using Keyword

C# Code Snippets Using Keyword
Share:

About

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.

Code:

[amp-gist id=”720a8c483e238742e80d44862721c25a”]

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger