12

Python has a nice keyword since 2.6 called with. Is there something similar in C#?

3 Answers3

23

The equivalent is the using statement

An example would be

  using (var reader = new StreamReader(path))
  {
    DoSomethingWith(reader);
  }

The restriction is that the type of the variable scoped by the using clause must implement IDisposable and it is its Dispose() method that gets called on exit from the associated code block.

Steve Gilham
  • 11,237
  • 3
  • 31
  • 37
9

C# has the using statement, as mentioned in another answer and documented here:

However, it's not equivalent to Python's with statement, in that there is no analog of the __enter__ method.

In C#:

using (var foo = new Foo()) {

    // ...

    // foo.Dispose() is called on exiting the block
}

In Python:

with Foo() as foo:
    # foo.__enter__() called on entering the block

    # ...

    # foo.__exit__() called on exiting the block

More on the with statement here:

ars
  • 120,335
  • 23
  • 147
  • 134
-1

As far as I know, there is one additional minor difference using using that others didn't mention.

C#'s using is meant to clean up "unmanaged resources" and while it's guaranteed will be called/disposed, its order / when it will be called isn't necessarily guaranteed.

So if you planned on Open/closing stuff in the right order in which they got called, you might be out of luck using using.

Source: Dispose of objects in reverse order of creation?

jeromej
  • 10,508
  • 2
  • 43
  • 62
  • The link you provide doesn't support your claim about `using` not guaranteeing when disposal happens. – user2357112 Dec 11 '18 at 21:10
  • The [Microsoft docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) say `using` is translated to a try-finally that calls `Dispose` in the `finally`, making cleanup deterministic. – user2357112 Dec 11 '18 at 21:11