C #3.0 Study Notes (1) Packaging of using statements and resources

Source: Internet
Author: User
Tags finally block

 

1. What is resource?

 

A resource is a class or structure that implements the System. IDisposable interface.

 

Ii. What is the role of the using statement?

 

The Using statement helps reduce potential problems caused by unexpected running errors. It neatly encapsulates the use of resources.

 

3. What is the usage form of the using statement?

 

Using (ResourceType Identifier = Expression)

 

{

 

Statement;

 

}

 

Note: 1. Allocate resources by code in parentheses.

 

2. Statement statements use resources.

 

4. How does the using statement work?

 

Implicitly call try... Finally... Exception handler, which puts the Statement into the try block and puts the Dispose method in the finally block to release resources in time.

 

5. Example of using statements?

 

The Code is as follows:

 

Class Program

 

{

 

Static voidMain (string [] args)

 

{

 

String path = @ "using.txt"; // it is best to indicate the Global Variation of the path string, which can be reused.

 

If (! File. Exists (path) // determines whether the File Exists. If the File does not exist, create the File and upload the characters. If the File does not exist, generate the token in the statement.

 

{

 

Using (TextWriter tw = File. CreateText (path ))

 

{

 

Tw. WriteLine ("using sentence example! ");

 

}

 

}

 

 

Using (TextReader tr = File. OpenText (path ))

 

{

 

String InputString;

 

While (InputString = tr. ReadLine ())! = Null)

 

{

 

Console. WriteLine (InputString );

 

Console. ReadKey ();

 

}

 

}

 

}

 

}

 

Output result:

 

Using sentence example!

 

 


The author's wheat forever.

Related Article

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.