Something I use a lot in Ruby:


File.open("something", "w+") { |output|
  output.puts("Hello, World!")
}
# File is now closed, and object not in scope.

I noticed that C# seems to have ‘using’, which I think works the same:


using (StreamWriter output = File.CreateText("something"))
{
  output.WriteLine("Hello, World!")
}
// I’m guessing that outputFile is no longer in scope and is closed.

Nice. Apparently VB.NET will get something similar soon.

The two implementations are probably dissimilar in some ways, for instance the Ruby version passes the block (the code between {}) to File.open.

Now I’m wondering why ‘using’ is needed at all. Wouldn’t this have the same effect?


{
  StreamWriter output = File.CreateText("something")
  output.WriteLine("Hello, World!")
}

Perhaps I’m thinking of C++, but surely the dtor (er, finalizer?) of ‘output’ is called when it goes out of scope, and that should close any internal handle if need be?

I’ve just been told that finalizers aren’t called until some unspecified point in the future. Perhaps that’s what ‘using’ is for - forcing the finalizer to be called immediately at the end of its scope?

No comments