views:

226

answers:

2

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

+19  A: 

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
+1  A: 

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