| by Arround The Web | No comments

C# Using Statement

When disposing of resources like database connections, document streams, or network connections, the “using” statement in the C# language is employed to ensure an appropriate disposal. The management of objects that comply with the IDisposable interface is made simpler by this approach. The section of code in which a resource is generated and utilized is created when any “using” statement is declared. If a normal processing or an exception is used to exit the block, the object’s Dispose() function is immediately invoked to release any uncontrolled resources and carry out any necessary cleaning. In this guide, we will cover the document stream resources with the use of the C# “using” statement.

Syntax:

The C# “using” statement is used to manage the resources that need to be explicitly dispose of conveniently and safely. It follows a specific syntax as follows:

using (ResourceType resource = new ResourceType()) { // Code }
  • The “using” keyword is used to declare the “using” statement.
  • After the “using” keyword, you specify the resource type that you want to work with, followed by a variable name that represents the resource within the block. Any object that carries out the IDisposable interface qualifies. You can operate on the resource within the block as necessary.
  • Next, an equal sign (=) is used to assign a new instance of the resource type to the variable.
  • Here, the “new” keyword is utilized to generate a new object of the resource type.
  • Any additional initialization or configuration can be performed within the parentheses after the new keyword.
  • Finally, you enclose the code that uses the resource within the curly braces {}.

Example 1:

Let’s begin with the C# code examples to demonstrate the utilization of the C# “using” statement in this article. The given code covers a C# program that reads the contents of a text file using the “StreamReader” class within a “using” statement.

The program starts by importing the necessary namespaces, System and System.IO, which provide classes for input/output operations and file handling. The program defines a class called “Dummy”. Inside the “Dummy” class, there is a Main() method which should always be treated as the entry for any C# program to execute the overall program from start to end.

The Main() method begins by declaring the “fp” string variable and assigning it the “test.txt” value. This represents the file path of the text file to be read. To cope with all possible errors that may arise when reading files, a try-catch block is utilized.

Within the try block, a “using” statement is used to create an instance of the “StreamReader” class. The task of comprehending the content from a file falls to the “StreamReader”. The file path that is stored in the “fp” variable is passed to the “StreamReader” constructor indicates the file to be read.

Inside the “using” block, the file’s contents are examined line by line using a “while” loop unless the final line of the document appears. The loop reads a line using the ReadLine() method of the “StreamReader” and assigns it to the string variable “l”. If the line is not null, it is printed to the console using the Console.WriteLine(l).

Once the end of the file is reached and there are no more lines to read, the “using” block is exited and the “StreamReader” object is automatically dispose of due to the “using” statement. The catch block is activated whenever an IOException arises while reading a document. The exception message is obtained using the e.Message, and an error message is displayed on the console using the Console.WriteLine().

The program execution completes and the console output is displayed. Assuming that the “test.txt” file exists and contains several lines of text, the output of this code is the contents of the file that are printed on the console as displayed in the following attached image. Every line is shown separately in the output:

using System;

using System.IO;

class Dummy {

  static void Main() {

   string fp = "test.txt";

   try {

    using (StreamReader reader = new StreamReader(fp))

     {

      string l;

        while ((l = reader.ReadLine()) != null)

        {

         Console.WriteLine(l);

         }

        }

     }

     catch (IOException e) {

       Console.WriteLine("Error Occured: " + e.Message);

     }

  }

}

Note: If the “test.txt” file does not exist or there is an issue with file access or reading, the catch block is executed, and an error message is displayed on the console that indicates the specific exception that occurred.

Example 2:

Here is another simple example that demonstrates the usage of the C# “using” statement with a StreamWriter to write the data to a file. Here’s an explanation of the code along with its expected output. The code starts with the declaration of the “Dummy” class and the “Main” method which will eventually start and end the program.

Within the “Main” method, the “fp” string variable is declared and initialized with the “test.txt” file path. The document that the information is written on is represented by this. To deal with any possible IOException that could arise throughout the document writing process, the program is enclosed in a try-catch block.

Inside the try block, a StreamWriter object named “writer” is created and initialized using the “using” statement. The StreamWriter is responsible for writing characters to a file. Two separate lines of content are added to a document inside the “using” section via the writer object’s WriteLine function. Once the block is exited, the Dispose() method of the StreamWriter is automatically called which ensures that any pending data is written to the file and the necessary resources are released.

Finally, outside the “using” block, the “Data written successfully.” message is shown on the console which demonstrates that the document’s write operation is successful and error-free. The catch block is activated if any IOException happens during the document’s write process. In that case, an error message along with the specific exception message is displayed on the console.

using System;

using System.IO;

class Dummy {

  static void Main() {

    string fp = "test.txt";

     try {

      using (StreamWriter writer = new StreamWriter(fp))

      {

        writer.WriteLine("Hello, C-Sharp!");

        writer.WriteLine("This is a test text.");

      }

      Console.WriteLine("Data written successfully.");

      }

      catch (IOException e) {

        Console.WriteLine("Error occurred: " + e.Message);

      }

  }

}

In summary, the code creates a StreamWriter object using the “using” statement, writes two lines of text to a file, and then automatically disposes of the StreamWriter. If the writing operation succeeds, the software generates a success message. Otherwise, it emits a failure message if any IOException occurs.

Conclusion

The C# “using” statement offers a practical and secure method of managing the resources that require an explicit disposal. You may guarantee that the necessary cleanup procedures are carried out automatically and reduce the likelihood of resource leaks by enclosing the resource consumption within a “using” block. This increases the dependability of your code.

Share Button

Source: linuxhint.com

Leave a Reply