The second is clearly better, and you can verify that it works fine by writing a test program.
The using
statement itself can't have a value, which is a limitation. Suppose you have a method called Open
that returns an open FileStream
, and you want to get the length of the file:
Console.WriteLine(Open().Length);
The bug there is that you aren't disposing the FileStream
. So you have to write (similar to your example):
long length;
using (FileStream file = Open())
length = file.Length;
Console.WriteLine(length);
But with a simple extension method, you can write this instead:
Console.WriteLine(Open().Use(file => file.Length));
Nice and neat, and the FileStream
gets properly disposed of.