Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

using statement - ensure the correct use of disposable objects

  • 2023-03-14
Feedback

In this article

Theusing statement ensures the correct use of anIDisposable instance:

var numbers = new List<int>();using (StreamReader reader = File.OpenText("numbers.txt")){    string line;    while ((line = reader.ReadLine()) is not null)    {        if (int.TryParse(line, out int number))        {            numbers.Add(number);        }    }}

When the control leaves the block of theusing statement, an acquiredIDisposable instance is disposed. In particular, theusing statement ensures that a disposable instance is disposed even if an exception occurs within the block of theusing statement. In the preceding example, an opened file is closed after all lines are processed.

Use theawait using statement to correctly use anIAsyncDisposable instance:

await using (var resource = new AsyncDisposableExample()){    // Use the resource}

For more information about using ofIAsyncDisposable instances, see theUsing async disposable section of theImplement a DisposeAsync method article.

You can also use ausingdeclaration that doesn't require braces:

static IEnumerable<int> LoadNumbers(string filePath){    using StreamReader reader = File.OpenText(filePath);        var numbers = new List<int>();    string line;    while ((line = reader.ReadLine()) is not null)    {        if (int.TryParse(line, out int number))        {            numbers.Add(number);        }    }    return numbers;}

When declared in ausing declaration, a local variable is disposed at the end of the scope in which it's declared. In the preceding example, disposal happens at the end of a method.

A variable declared by theusing statement or declaration is readonly. You cannot reassign it or pass it as aref orout parameter.

You can declare several instances of the same type in oneusing statement, as the following example shows:

using (StreamReader numbersFile = File.OpenText("numbers.txt"), wordsFile = File.OpenText("words.txt")){    // Process both files}

When you declare several instances in oneusing statement, they are disposed in reverse order of declaration.

You can also use theusing statement and declaration with an instance of aref struct that fits the disposable pattern. That is, it has an instanceDispose method, which is accessible, parameterless and has avoid return type.

Theusing statement can also be of the following form:

using (expression){    // ...}

whereexpression produces a disposable instance. The following example demonstrates that:

StreamReader reader = File.OpenText(filePath);using (reader){    // Process file content}

Warning

In the preceding example, after control leaves theusing statement, a disposable instance remains in scope while it's already disposed. If you use that instance further, you might encounter an exception, for example,ObjectDisposedException. That's why we recommend declaring a disposable variable within theusing statement or with theusing declaration.

C# language specification

For more information, seeThe using statement section of theC# language specification and the proposal note about"pattern-based using" and "using declarations".

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo