1

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.

16
  • 4
    So you mean new MyDisposable().Dispose();? Commented Jan 19, 2022 at 14:39
  • 3
    I mean, by your own admission this isn’t sane, so why would special syntax exist to support it? Commented Jan 19, 2022 at 14:40
  • 2
    How about: using (new MyDisposable()) {} Commented Jan 19, 2022 at 14:47
  • 2
    Side effects are already a code smell, but being only interested in size effects is the extreme version. You should definitely refactor to another solution, because this doesn't sound like a good design. Commented Jan 19, 2022 at 14:54
  • 1
    @JHBonarius I can think of an use here: C++-like scope locks. public MyDisposable() { Monitor.Enter(o); } public void Dispose(){ Monitor.Exit(o); } That may come in useful in one form or another. Commented Jan 19, 2022 at 15:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.