Function of the using keyword in C #

Source: Internet
Author: User

In C #, using has two functions. 1. Used as a command to reference namespaces, such as using system. IO;

2. As a statement, using defines a range. After exiting using, an object is automatically released after the end of the range, which plays a role of automatically releasing resources. For example, the author uses the writeline method in the streamwriter column to write data to a specified text file first, and then calls the readtoend method of streamreader to read data from the specified text file. When using the using statement, the system first allocates resources to the using code block. After the using code block is generated, the resources allocated to the code block are automatically released because of the using statement, it mainly plays a role in Automatic Resource release and reduces system overhead.

Static void main (string [] ARGs)

{

String strfile = appdomain. currentdomain. setupinformation. applicationbase + "\ test.txt ";

// Specify test.txt in the current example

Try

{

// Check whether the file exists. If yes, delete it first and assign new content to the specified text file.

If (file. exists (strfile ))
{
File. Delete (strfile );

}

// Instantiate streamwriter and write data to a text file

Using (streamwriter Sw = new streamwriter (strfile ))
{
Sw. writeline! ");
Sw. writeline ("poor and strong, don't fall into the cloud! ");

}

// Instantiate streamreader and use the readtoend method to read and output data from the text file from start to end

Using (streamreader sr = new streamreader (strfile ))
{
Console. writeline (Sr. readtoend ());
}
}
Catch (exception ex)
{
Console. writeline (ex. Message );

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.