Syntax for using declaration without variable

315 Views Asked by At

Consider a disposable with side effects in the constructor:

public class MyDisposable : IDisposable
{
    public MyDisposable()
    {
        // Some side effects
        ...
    }

    public void Dispose()
    {
        ...
    }
}

If I'm only interested in the side effects I can, in some method, use the class like so:

using var _ = new MyDisposable();
using var __ = new MyDisposable();
using var ___ = new MyDisposable();

Is there some syntax to avoid declaring the variables as they are unused? Something like:

using new MyDisposable();
using new MyDisposable();
using new MyDisposable();

I'm only interested in if there is such a syntax. I'm not looking for a way to restructure the code into a more sane approach.

1

There are 1 best solutions below

0
Olivier Jacot-Descombes On

The using statement works without variable declation:

using (new MyDisposable()) {
    Console.WriteLine("in using");
}

You can test it with this class:

public class MyDisposable : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Dispose");
    }
}

and this console app:

Console.WriteLine("Start");
using (new MyDisposable()) {
    Console.WriteLine("in using");
}
Console.WriteLine("End");
Console.ReadKey();

It prints:

Start
in using
Dispose
End