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 filesnetwork 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:

using System; // <= The "using" keyword can be used as a directive to include a namespace,
using System.IO;

namespace UsingKeyword
{
    class Program
    {
        static void Main(string[] args)
        {

            //or it can be used as a statement. 
            //Using 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, ...

            using (StreamWriter writer = new StreamWriter(@"C:\users\DTPC\Desktop\myFile.txt"))
            {
                writer.WriteLine("Some text.");
            }

            //
            //The code above is almost the same as the code bellow, just more compact.
            //

            StreamWriter writer2 = null;

            try
            {
                writer2 = new StreamWriter(@"C:\users\DTPC\Desktop\myFile2.txt");
                writer2.WriteLine("Some other text.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
            finally
            {
                //This always executes.
                if (writer2 != null)
                {
                    writer2.Close();
                    writer2.Dispose();
                }
            }
        }
    }
}

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