When does IDE0063 dispose?

Bizhan picture Bizhan · Aug 12, 2019 · Viewed 9.3k times · Source

I'm trying to understand this C# 8 simplification feature:

IDE0063 'using' statement can be simplified

For example, I have:

void Method()
{
    using (var client = new Client())
    {
        // pre code...
        client.Do();
        // post code...
    } --> client.Dispose() was called here.
    // more code...
}

IDE tells me I can simplify this using statement by writing this instead:

void Method()
{
    using (var client = new Client());
    // pre code...
    client.Do();
    // post code...
    // more code...
}

I can't understand how it works and how it decides I'm not using the variable anymore. More specifically, when exactly does it call client.Dispose method?

Answer

Henk Holterman picture Henk Holterman · Aug 12, 2019

You are using C# 8. In older C# versions that ; would have made this invalid.

In the new syntax, the client stays in scope for the surrounding method (or other {} scope block). Note that you can omit the outer pair of () as well.

It's called a using declaration, the documentation is here.

void Method()
{
    using var client = new Client();
    // pre code...
    client.Do();
    // post code...
    // more code...
} --> client.Dispose() is called here (at the latest)

Logically the Dispose happens at the } but the optimizer might do it earlier.

Edit

I noticed that having // more code after the end of the using block, prevents this improvement from appearing. So there will be no more ambiguity if you convert the following code:

void Method()
{
    // not relevant code

    using (var client = new Client())
    {
        // pre code...
        client.Do();
        // post code...
    }
}

into this code:

void Method()
{
    // not relevant code

    using var client = new Client();
    // pre code...
    client.Do();
    // post code...
}